<?php if (!defined('TL_ROOT')) die('You can not access this file directly!');


/**
 * This class is for online shop order process - payment.
 * params order step
 * This is the children of controller.
 * PHP5 CMS Typolight
 * Copyright is 34n.sam@gmail.com
 */
 
 /**
 * Start page
 */
session_start();

class Validation extends Controller
{
	/**
	 * This is class construct function.
	 * @params null
	 * @Return null
	 */
	public function __construct()
	{
		parent::__construct();
		header('Cache-Control: no-store, no-cache, must-revalidate');
		require_once('system/libraries/currency.php');
		$this->obj_currency = new Currency();		
	}
	
	/** 
	 * Start page function
	 * @params null
	 * @Return null
	 */
	public function run()
	{
		// Check shopping cart.
		if (!isset($_SESSION['cart']) || !$_SESSION['cart'])
		{
			$this->redirect('shoppingcart.html');
		}
		
		if (isset($_GET['action']) && $_GET['action'] == "ajax_shipping")
		{
			echo $this->ajax_shipping_change($_POST);exit;
		}
			
		if (isset($_GET['method']) && $_GET['method'])
		{
			switch (trim($_GET['method']))
			{
				case 'COD':
					if (!isset($_POST) || !$_POST['confirm'])
					{
						$discount = 0.00;						
						$strHtml = $this->generateCOD($discount, $is_voucher_exist);
						echo $strHtml;
					}
					else
					{
						$this->generateOrder();
					}
					break;
				case 'Paypal':
					if (!isset($_POST) || !$_POST['confirm'])
					{
						$discount = 0.00;
						
						$strHtml = $this->generatePaypal($discount, $is_voucher_exist);
						echo $strHtml;
					}
					else
					{
						$this->generateOrder();
					}
					break;
				case 'Alipay':
					if (!isset($_POST) || !$_POST['confirm'])
					{
						$discount = 0.00;						
						$strHtml = $this->generateAlipay($discount, $is_voucher_exist);
						echo $strHtml;
					}
					else
					{
						$this->generateOrder();
					}
					break;
				default:
					break;
			}
		}
	}
	
	/**
	 * 由于免运费导致的优惠值的改变
	 * @param post 数组
	 * @return string html
	 */
	private function ajax_shipping_change($arr)
	{
		$this->import('Database');
		
		$obj_shipping = $this->Database->prepare("SELECT * FROM tl_shippings WHERE id=?")
										->execute($arr['shipping_id'], time(), time());
		$cnt = $this->get_shipping_cart_cnt($_SESSION['cart']);
		$arr_shippings = array(
			'firstprice'=>$obj_shipping->firstprice, 
			'continueprice'=>$obj_shipping->continueprice,
		);
		$_SESSION['ORDER']['shipping'] = $tmp_order_shipping = $this->get_shipping_fee($_SESSION['cart'], $id_area, $arr['shipping_id'], $arr_shippings, $cnt);
		$this->discount_total($arr['amount'], $discount, $is_free_shipping, $is_exist_coupon);

		$strHtml = "<div class=\"count_price\">
				<p>SUBTOTAL: <span>" . $this->obj_currency->change_order($_SESSION['ORDER']['totalPrice'],$_COOKIE['PAY_CURRENCY']) . "</span></p>
				<p>SHIPPING: <span id='total_shipping'>" . $this->obj_currency->change_order(number_format(floatval($_SESSION['ORDER']['shipping']), 2, '.', ''),$_COOKIE['PAY_CURRENCY']) . "</span></p>
				<p class=\"order_givevoucher\"" . (($discount == 0.00) ? " style=\"display:none\"" : "") . ">GIFT VOUCHER: <span>- " . $this->obj_currency->change_order(number_format(floatval($discount), 2, '.', ''),$_COOKIE['PAY_CURRENCY']) . "</span></p>
			</div> <!-- order_price end -->
			<div class=\"total_price\">
				<small>TOTAL //</small>
				<span><span id=\"total_cost\">" . $this->obj_currency->change_order(number_format(floatval($_SESSION['ORDER']['totalPrice'] + $_SESSION['ORDER']['shipping'] - $discount), 2, '.', ''),$_COOKIE['PAY_CURRENCY']) . "</span><input type='hidden' value='" . $_SESSION['ORDER']['shipping'] . "' /></span>
			</div> <!-- total_price end -->";
		
		return $strHtml;
	}
	
	/**
	 * 得到购物车数量，以便计算配送费用
	 * @param mixed shipping cart data
	 * @return int 购物车总数量
	 */
	private function get_shipping_cart_cnt($arr_cart=array())
	{
		if (!$arr_cart)
			return 0;
		
		$cnt = 0;
		foreach ((array)$arr_cart as $arr)
		{
			if (is_array($arr))
				$cnt = $cnt + intval($arr['quantity']);
		}
		
		return $cnt;
	}
	
	/**
	 * 计算订单配送费用
	 * @param array - shipping cart
	 * @param string - area id
	 * @param string - biggest catalog id
	 * @param array - 选中的配送方式信息
	 * @param array - 购物车数量
	 */
	private function get_shipping_fee($arr_cart=array(), $id_area=0, $shipping_pid, $arr_select_shipping, $cnt=0)
	{
		if ($cnt < 1)
			return $arr_select_shipping['firstprice'];
			
		$is_bigger = true;
		$objSelectShipping = $this->Database->prepare("SELECT * FROM tl_shippings WHERE `id`=?")
											->execute($_SESSION['ORDER']['id_carrier']);
		
		$arr_other_shipping = array();
		$continue_prices = 0;
		foreach ($arr_cart as $key=>$arrCatalogInfo)
		{				
			if ($key == 'sessionID')
				continue;
			if ($shipping_pid == $arrCatalogInfo['id'])
				if ($arrCatalogInfo['quantity'] <= 1)
					continue;
				else
				{
					$arrCatalogInfo['quantity']--;
				}
			
			// Get shipping area
			$obj_catalogs = $this->Database->prepare("SELECT * FROM product_catalog WHERE id=?")
												->execute($arrCatalogInfo['id'],time(),time());
			if (!$obj_catalogs->programe)
			{
				$obj_programmes = $this->Database->prepare("SELECT * FROM tl_programmes WHERE is_default='true'")
												->execute(time(),time());
				$obj_catalogs->programe = $obj_programmes->id;
			}
			
			// generate shipping method.
			$tmp_arr = array();
			$select_shipping_arr = array();
			$first_price = 0;
			if ($id_area)
			{
				$objShippings = $this->Database->prepare("SELECT * FROM tl_shippings WHERE area=? AND pid=? AND `id_real`=? ORDER BY sort,name")
											->execute($id_area, $obj_catalogs->programe, $objSelectShipping->id_real, time(), time());
				if ($objShippings->numRows > 0)
				{
					while ($objShippings->next())
					{
						$continue_prices += $objShippings->continueprice*$arrCatalogInfo['quantity'];
					}
				}
			}
		}
		
		$ship_fee = $arr_select_shipping['firstprice'] + $continue_prices;		
		
		return $ship_fee;
	}
	
	/**
	 * Generate the discount amount
	 * @param string amount
	 * @param string discount
	 * @param boolean freeshipping or not.
	 * @param boolean exisit coupon or not.
	 * @return null
	 */
	private function discount_total($amount='0.00', &$discount, &$is_free_shipping, &$is_exist_coupon)
	{
		$this->import('Database');		
		
		$time = time();
		$obj_pmt_orders = $this->Database->prepare("SELECT * FROM tl_pmt_order WHERE `pmt_from` < ? AND `pmt_to` >= ? ORDER BY pmt_con ASC,priority ASC")
											->execute($time, $time);
								
		$has_free_shipping = false;
		$dis_tmp = 0;
		$arr_discount = array();
		
		$_is_order_promotion = false;
		if ($obj_pmt_orders->numRows >= 1)
		{
			$pmt_obj = '';
			while ($obj_pmt_orders->next())
			{
				if ($pmt_obj != $obj_pmt_orders->pmt_con)
				{
					$arrPromotion = array(
						'pmt_con' => $obj_pmt_orders->pmt_con,
						'pmt_amout' => $obj_pmt_orders->pmt_amout,
						'method' => $obj_pmt_orders->pmt_method,
						'discount' => $obj_pmt_orders->discount,
					);
					
					$_is_order_promotion = $this->promotion_count($arrPromotion, $amount, $dis_tmp, $has_free_shipping, $is_exist_coupon);
					if ($has_free_shipping) $is_free_shipping = true;
					$discount += $dis_tmp;
					if ($amount - $discount > 0)
						$amount = $amount - $discount;
					
					$arr_discount[$obj_pmt_orders->pmt_con] = true;
					$pmt_obj = $obj_pmt_orders->pmt_con;
					if ($_is_order_promotion) break;
				}
			}
		}
		
		// 使用coupon.
		if ($_POST['vourcher'])
		{
			unset($_SESSION['ORDER']['vourcher']);
			$_SESSION['ORDER']['vourcher'][] = $_POST['vourcher'];
		}
		
		if ($_SESSION['ORDER']['vourcher'])
			foreach ($_SESSION['ORDER']['vourcher'] as $vourcher)
			{
				$obj_member = $this->Database->prepare("SELECT email FROM tl_member WHERE id=?")
											->execute($_SESSION['ORDER']['mem_id']);
				$time = time();
				$obj_voucher = $this->Database->prepare("SELECT * FROM tl_voucher WHERE email=? AND coupon_code=? AND `coupon_from` < ? AND `coupon_to` >= ? AND `current_use` < `use_times`")
												->execute($obj_member->email, $vourcher, $time, $time);
				
				if ($obj_voucher->numRows >= 1 && !$arr_discount[$obj_voucher->pmt_con])
				{
					$arrCoupon = array(
						'pmt_con' => $obj_voucher->coupon_con,
						'pmt_amout' => $obj_voucher->coupon_amount,
						'method' => $obj_voucher->coupon_method,
						'discount' => $obj_voucher->discount,
					);
					
					$this->promotion_count($arrCoupon, $amount, $dis_tmp, $has_free_shipping, $is_exist_coupon);
					if ($has_free_shipping) $is_free_shipping = true;
					$discount += $dis_tmp;
					$arr_discount[$obj_voucher->pmt_con] = true;
					
					if ($amount - $discount > 0)
						$amount = $amount - $discount;
					
					$is_exist_coupon = true;
				}
				
				$obj_voucher = $this->Database->prepare("SELECT * FROM tl_voucher WHERE email=? AND coupon_code=? AND `coupon_from` < ? AND `coupon_to` >= ?")
												->execute('', $vourcher, $time, $time);
				if ($obj_voucher->numRows >= 1 && !$arr_discount[$obj_voucher->pmt_con])
				{
					$arrCoupon = array(
						'pmt_con' => $obj_voucher->coupon_con,
						'pmt_amout' => $obj_voucher->coupon_amount,
						'method' => $obj_voucher->coupon_method,
						'discount' => $obj_voucher->discount,
					);
					
					$this->promotion_count($arrCoupon, $amount, $dis_tmp, $has_free_shipping, $is_exist_coupon);
					if ($has_free_shipping) $is_free_shipping = true;
					$discount += $dis_tmp;
					$arr_discount[$obj_voucher->pmt_con] = true;
					
					if ($amount - $discount > 0)
						$amount = $amount - $discount;
					
					$is_exist_coupon = true;
				}
			}		
		
		return $free_shipping;
	}
	
	/**
	 * 计算优惠条件的统一方法
	 * @param array 优惠条件的数据数组
	 * @param string 总金额
	 * @param string 引用变量 优惠值
	 * @param boolean fee shipping or not
	 * @return null
	 */
	private function promotion_count($arr_promotion, $amount, &$discount, &$is_free_shipping)
	{
		$is_free_shipping = false;
		$is_promotion = false;
		switch ($arr_promotion['pmt_con'])
		{
			case '1':
				switch ($arr_promotion['method'])
				{
					case '1':
						// 优惠金额
						$discount = $arr_promotion['discount'];
						$is_promotion = true;
						break;
					case '2':
						// 折扣
						$discount = $amount * $arr_promotion['discount'];
						$is_promotion = true;
						break;
				}
				if ($discount > $amount) $discount = $amount;
				break;
			case '2':
				// 订单满xxx元的优惠条件...
				if ($amount > floatval($arr_promotion['pmt_amout'])|| $arr_promotion['pmt_amout'] === 0)
				{
					switch ($arr_promotion['method'])
					{
						case '1':
							// 优惠金额
							$discount = $arr_promotion['discount'];
							$is_promotion = true;
							break;
						case '2':
							// 折扣
							$discount = $amount * $arr_promotion['discount'];
							$is_promotion = true;
							break;
					}							
				}
				if ($discount > $amount) $discount = $amount;
				break;
			case '3':
				// 订单全场免运费.
				$discount = $_SESSION['ORDER']['shipping'];
				$is_free_shipping = true;
				$is_promotion = true;
				break;
		}
		
		return $is_promotion;
	}
	
	/**
	 * Generate the Paypal method.
	 * @params null
	 * @Return html string
	 */
	private function generatePaypalForm($order_id=0, $discount=0)
	{
		$this->import('Database');
		$objMember = $this->Database->prepare("SELECT * FROM tl_member WHERE id=?")
									->execute($_SESSION['ORDER']['mem_id']);
		if ($objMember->numRows < 1)
			return "";
		
		$objCurrency = $this->Database->prepare("SELECT * FROM tl_currency WHERE iso_code=?")
										->execute('USD');
		$fee_rate = floatval($objCurrency->conversion_rate);
		$total_order = number_format(floatval($_SESSION['ORDER']['totalPrice'])*$fee_rate, 2, '.', '');
		$total_shipping = number_format(floatval($_SESSION['ORDER']['shipping'])*$fee_rate, 2, '.', '');
		$discount = number_format(floatval($discount)*$fee_rate, 2, '.', '');
		
		$strHTML = "<html><body><form id=\"paypal_form\" name=\"paypal_form\" class=\"hidden\" style=\"display:none;\" method=\"post\" action=\"https://www.paypal.com/cgi-bin/webscr\">";		
		$strHTML .= "<input type=\"hidden\" value=\"janelou@gmail.com\" name=\"business\"/>
		<input type=\"hidden\" value=\"janelou@gmail.com\" name=\"receiver_email\"/>
		<input type=\"hidden\" value=\"_xclick\" name=\"cmd\"/>
		<input type=\"hidden\" value=\"USD\" name=\"currency_code\"/>
		<input type=\"hidden\" value=\"Payment:" . $order_id . "\" name=\"item_name\"/>
		<input type=\"hidden\" value=\"" . $order_id . "\" name=\"item_number\"/>
		<input type=\"hidden\" value=\"" . ($total_order + $total_shipping - $discount) . "\" name=\"amount\"/>
		<input type=\"hidden\" value=\"" . $this->Environment->base . "thankyou.html?method=Paypal\" name=\"return\"/>
		<input type=\"hidden\" value=\"" . $this->Environment->base . "validate_server.php?method=Paypal\" name=\"notify_url\"/>
		<input type=\"hidden\" value=\"US\" name=\"lc\"/>
		</form>";
		
		$strHTML .= "<script type=\"text/javascript\">document.paypal_form.submit();</script></body></html>";
		
		unset($_SESSION['cart']);
		unset($_SESSION['ORDER']);
		unset($_SESSION['CARTQUANTITY']);
			
		return $strHTML;
	}
	
	/**
	 * Generate the Paypal method.
	 * @params null
	 * @Return html string
	 */
	private function generateAlipayForm($order_id=0, $discount=0)
	{
		$total_order = number_format(floatval($_SESSION['ORDER']['totalPrice']), 2, '.', '');
		$total_shipping = number_format(floatval($_SESSION['ORDER']['shipping']), 2, '.', '');		
        $mer_id = '2088202305942331';
        $mer_key = 'dq1mexi208a0l9f9irpizx49szj2rjld'; 
        $subject = 'Alipay'.$order_id;
        $subject = str_replace("'",'`',trim($subject));
        $subject = str_replace('"','`',$subject);
		
		$return['service'] = 'create_direct_pay_by_user';
		$return['logistics_type'] = 'POST';
		$return['logistics_payment'] = 'BUYER_PAY';
		$return['logistics_fee'] = '0.00';
		$return['agent'] = 'C433530444855584111X';
		$return['payment_type'] = '1';
		$return['partner'] = $mer_id;
		$return['return_url'] = $this->Environment->base . "thankyou.html?method=Alipay";
		$return['notify_url'] = $this->Environment->base . "validate_server.php?method=Alipay";
		$return['subject'] = $subject;
		$return['body'] = 'Daftshopping order';
		$return['out_trade_no'] = $order_id;
		$return['price'] = number_format(($total_order + $total_shipping - $discount), 2, '.', '');
		$return['quantity'] = '1';
		$return['seller_id'] = $mer_id;
		$return['buyer_msg'] = 'No message';
		$return['_input_charset'] = 'utf-8';
		ksort($return);
        reset($return);    
        $mac= "";
        foreach($return as $k=>$v){
            $mac .= "&{$k}={$v}";
        }
        $mac = substr($mac,1);
        $mac = md5($mac.$mer_key);  //验证信息         
		$return['sign'] = $mac;
		$return['sign_type'] = 'MD5';
		
		$strHTML = "<html><body><form id=\"alipay_form\" name=\"alipay_form\" class=\"hidden\" style=\"display:none;\" method=\"post\" action=\"https://www.alipay.com/cooperate/gateway.do?_input_charset=utf-8\">";		
		$strHTML .= "<input type=\"hidden\" value=\"" . $return['service']. "\" name=\"service\"/>
		<input type=\"hidden\" value=\"" . $return['logistics_type'] . "\" name=\"logistics_type\"/>
		<input type=\"hidden\" value=\"" . $return['logistics_payment'] . "\" name=\"logistics_payment\"/>
		<input type=\"hidden\" value=\"" . $return['logistics_fee'] . "\" name=\"logistics_fee\"/>
		<input type=\"hidden\" value=\"" . $return['agent'] . "\" name=\"agent\"/>
		<input type=\"hidden\" value=\"" . $return['payment_type'] . "\" name=\"payment_type\"/>
		<input type=\"hidden\" value=\"" . $return['partner'] . "\" name=\"partner\"/>
		<input type=\"hidden\" value=\"" . $return['return_url'] . "\" name=\"return_url\"/>
		<input type=\"hidden\" value=\"" . $return['notify_url'] . "\" name=\"notify_url\"/>
		<input type=\"hidden\" value=\"" . $return['subject'] . "\" name=\"subject\"/>
		<input type=\"hidden\" value=\"" . $return['body'] . "\" name=\"body\"/>
		<input type=\"hidden\" value=\"" . $return['out_trade_no'] . "\" name=\"out_trade_no\"/>
		<input type=\"hidden\" value=\"" . $return['price'] . "\" name=\"price\"/>	
		<input type=\"hidden\" value=\"" . $return['quantity'] . "\" name=\"quantity\"/>
		<input type=\"hidden\" value=\"" . $return['seller_id'] . "\" name=\"seller_id\"/>
		<input type=\"hidden\" value=\"" . $return['buyer_msg'] . "\" name=\"buyer_msg\"/>
		<input type=\"hidden\" value=\"" . $return['sign'] . "\" name=\"sign\"/>
		<input type=\"hidden\" value=\"" . $return['sign_type'] . "\" name=\"sign_type\"/>
		</form>"; 
		$strHTML .= "<script type=\"text/javascript\">document.alipay_form.submit();</script></body></html>";
		
		unset($_SESSION['cart']);
		unset($_SESSION['ORDER']);
		unset($_SESSION['CARTQUANTITY']);
			
		return $strHTML;
	}
	
	/**
	 * Generate and judge validation cod payment, and generate cod.
	 * @params float discount value
	 * @Return null
	 */
	public function generateCOD($discount = 0.00, $is_voucher_exist=false)
	{
		$countries = array();
		$this->import("Database");
		$this->loadLanguageFile('countries');
		include(TL_ROOT . '/system/config/countries.php');
		
		// Get the shiping address.
		$objShippingAddr = $this->Database->prepare("SELECT * FROM tl_address_book WHERE id=?")
											->execute($_SESSION['ORDER']['address_shipping']);
		if ($objShippingAddr->numRows < 1)
			return;
		
		// Get the states.
		$arrStates = array();
		$objStates = $this->Database->prepare("SELECT * FROM `china_province` ORDER BY `province_en`")
									->execute(time());
		
		while ($objStates->next())
		{
			$arrStates[$objStates->id] = stripslashes($objStates->province_en);
		}
		
		// Get State.
		$arrCitys = array();			
		$objCitys = $this->Database->prepare("SELECT * FROM `china_city` ORDER BY `city_en`")
									->execute(time());
		
		while ($objCitys->next())
		{
			$arrCitys[$objCitys->id] = stripslashes($objCitys->city_en);
		}
									
		if($objShippingAddr->street_2=="line 2" || $objShippingAddr->street_2=="Address line 2") {
			$street = $objShippingAddr->street . ", ";
		}else{
			$street = $objShippingAddr->street . ", <br />" .$objShippingAddr->street_2;
		}
		
		/** purchase the category information and shipping information **/
		$arrCatalog = $_SESSION['cart'];
		$shipping_pid = 0;
		$bigger_catalog_price = 0;
		foreach ($arrCatalog as $key=>$arrCatalogInfo)
		{				
			if ($key == 'sessionID')
				continue;
				
			$catalogStock = 0;
			$is_noneStock = false;
			$is_overStock = false;
			
			// Judge the update information
			if ($this->Input->get('generateOrder'))
			{
				switch ($this->Input->get('generateOrder'))
				{
					case 'success':
						break;
					case 'failure':
						if (!$this->Input->get('stock'))
						{
							if ($arrCatalogInfo['id'] == $this->Input->get('id_catalog'))
								$is_noneStock = true;
						}
						else
							if ($arrCatalogInfo['id'] == $this->Input->get('id_catalog'))
								$is_overStock = true;
						break;
					default:
						break;
				}
			}
			// Get the stock of this catalog.
			$catalogStock = $this->getCurrentStockInfo($arrCatalogInfo['id'], $arrCatalogInfo['colour'], $arrCatalogInfo['size']);
			
			// Stock information deal with.
			if (is_null($catalogStock))
			{
				continue;
			}
			elseif (!$catalogStock)
			{
				$is_noneStock = true;
			}
			else 
			{
				$is_noneStock = false;
				if (intval($arrCatalogInfo['quantity']) > $catalogStock)
				{
					$_SESSION['cart'][$key]['quantity'] = $catalogStock;
					$is_overStock = true;
				}
				else 
					$is_overStock = false;
			}
			// Get catalog size.
			$objCatalogSize = $this->Database->prepare("SELECT * FROM catalog_size WHERE id=?")
											->execute($arrCatalogInfo['size']);
			$objCurrentCatalog = $this->Database->prepare("SELECT * FROM product_catalog WHERE id=?")
											->execute($arrCatalogInfo['id']);
			$objCataColor = $this->Database->prepare("SELECT `id` FROM `catalog_colour` WHERE `title`=?")
											->execute($arrCatalogInfo['colour']);
											
			$imgPath = "daft_files/catalog/products/" . $arrCatalogInfo['skuid'] . "/" . $arrCatalogInfo['colour'] . "/1.jpg";
			
			$str_category_Html .= "<div class=\"error\"" . ((!$is_noneStock) ? ' style="display:none;"' : '') . ">The quantity of this product is out of stock. Please select again.</div>
						<div class=\"error\"" . ((!$is_overStock) ? ' style="display:none;"' : '') . ">The quantity of current product has overd the stock. Please select another product.</div>
				<table class=\"cart_item\">
				<tr>
					<td rowspan=\"2\" class=\"td_pic\"><a href=\"./product.html?category=".$objCurrentCatalog->category."&id=". $objCurrentCatalog->id . "&id_colour=" . $objCataColor->id . "&id_size=" . $arrCatalogInfo['size'] . "\" target=\"_blank\"><img src=\"image.php?src=" . $imgPath . "&width=79&height=79\" alt=\"\" /></a></td>
					<td class=\"td_info\">
						<h4><a href=\"./product.html?category=".$objCurrentCatalog->category."&id=". $objCurrentCatalog->id . "&id_colour=" . $objCataColor->id . "&id_size=" . $arrCatalogInfo['size'] . "\" target=\"_blank\">" . $arrCatalogInfo['name'] . "</a></h4>
						<small>SKU #" . $arrCatalogInfo['skuid'] . "</small><br />
						<small>" . $this->obj_currency->change_order($arrCatalogInfo['price'],$_COOKIE['PAY_CURRENCY'])  . "</small>" . (($arrCatalogInfo['gift_wrapping']) ? "<br /><small>GIFT WRAPPING "
						 . $this->obj_currency->change_order(number_format(floatval($arrCatalogInfo['gwPrice']), 2, '.', ''),$_COOKIE['PAY_CURRENCY']) . "</small>" : "") . "
					</td>
					<td rowspan=\"2\" class=\"td_skin\">
						<div class=\"skin\">
							<p>
								<label>COLOR</label>
								<span class=\"skin_value\">" . $arrCatalogInfo['colour'] . "</span>
							</p>
							<p>
								<label>SIZE</label>
								<span class=\"skin_value\">" . $objCatalogSize->size . "</span>
							</p>
							<p>
								<label>QUANTITY</label>
								" . ((!$is_noneStock) ? ("
								<span class=\"skin_value\">" . $arrCatalogInfo['quantity'] . "</span>") : "<span class=\"error\">Out of stock - Please remove from your cart.</span>") . "
							</p>
						</div>
					</td>
					<td rowspan=\"2\" class=\"unit_price\"><strong>" . $this->obj_currency->change_order(number_format(floatval($arrCatalogInfo['price']) * floatval($arrCatalogInfo['quantity'])+$arrCatalogInfo['gwPrice'], 2, '.', ''),$_COOKIE['PAY_CURRENCY'])  . "</strong></td>
				</tr> 
			</table>";
			
			if ($arrCatalogInfo['price'] > $bigger_catalog_price)
			{
				$shipping_pid = $objCurrentCatalog->id;
				$bigger_catalog_price = $arrCatalogInfo['price'];
			}
		}
		
		$str_category_Html .= "<p class=\"cart_navigation\"></p>";
		
		// generate shipping method.
		// Get shipping area
		$obj_catalogs = $this->Database->prepare("SELECT * FROM product_catalog WHERE id=?")
											->execute($shipping_pid,time(),time());
		if (!$obj_catalogs->programe)
		{
			$obj_programmes = $this->Database->prepare("SELECT * FROM tl_programmes WHERE is_default='true'")
											->execute(time(),time());
			$obj_catalogs->programe = $obj_programmes->id;
		}
		$id_area = 0;
		$obj_shipping_area = $this->Database->prepare("SELECT area.`id` 
														FROM tl_areas AS area 
														INNER JOIN tl_countries AS country ON country.id_area = area.id 
														WHERE country.name=?")
											->execute($objShippingAddr->country);
		if ($obj_shipping_area->numRows > 0)
		{
			$id_area = $obj_shipping_area->id;
		}
		
		// generate shipping method.
		if ($id_area)
		{
			$objShippings = $this->Database->prepare("SELECT * FROM tl_shippings WHERE area=? AND pid=? ORDER BY sort,name")
										->execute($id_area, $obj_catalogs->programe, time(), time());
			if ($objShippings->numRows > 0)
			{
				while ($objShippings->next())
				{
					$arr_id_shppings[] = $objShippings->id;
					$arr_shippings[$objShippings->id] = array(
						'id'=>$objShippings->id,
						'firstprice'=>$objShippings->firstprice,
						'continueprice'=>$objShippings->continueprice,
					);
				}
				if (!in_array((int)$_SESSION['ORDER']['id_carrier'], $arr_id_shppings))
				{
					$_SESSION['ORDER']['id_carrier'] = $arr_id_shppings[0];
				}
			}
		}
		$objShippings = $this->Database->prepare("SELECT * FROM tl_shippings WHERE pid=? ORDER BY sort,name")
										->execute($obj_catalogs->programe, time(), time());
		if (isset($_SESSION['ORDER']['id_carrier']) && $_SESSION['ORDER']['id_carrier'])
			$id_carrier = $_SESSION['ORDER']['id_carrier'];
		
		if ($objShippings->numRows >= 1)
		{
			/*$str_category_Html .= '<div id="shipping_area"><table><tbody>';
			$index = 0;
			while($objShippings->next())
			{
				if (!$id_carrier)
					$id_carrier = $objShippings->id;
				
				if ($id_area && $objShippings->area != $id_area)
					continue;
					
				$cnt = $this->get_shipping_cart_cnt($_SESSION['cart']);
				$shipping_fee = $this->get_shipping_fee($objShippings->firstprice, $objShippings->continueprice, $cnt);
				$shipping_fee = number_format($shipping_fee, 2, '.', '');
				
				$str_category_Html .= '<tr>
										<td class="td1"><input type="radio" ship_id="' . $objShippings->id . '" id="shipping_' . $objShippings->id . '" name="shipping" class="radio" value="' . $shipping_fee . '"' . (($index == 0 || $_SESSION['ORDER']['id_carrier'] == $objShippings->id) ? ' checked="checked"' : '') . ' /><input type="hidden" value="' . $objShippings->id . '" /></td>
										<td class="td2">' . $objShippings->name . '&nbsp;' . $objShippings->des . '</td>
									</tr>';
									
				$index++;
			}
			$str_category_Html .= '</tbody></table></div>';*/
		}
		/** end **/
		
		$obj_select_shipping = $this->Database->prepare("SELECT * FROM `tl_shippings` WHERE `id`=?")
											->execute($id_carrier);
		$obj_currency = $this->Database->prepare("SELECT * FROM `tl_currency` WHERE `is_default`=1")
										->execute(time());
											
		$strHtml = "<form id=\"validate_form\" method=\"post\" action=\"".$this->Environment->base."validation.html?method=COD\">
		<input type=\"hidden\" value=\"1\" name=\"confirm\"/>
		<input type=\"hidden\" value=\"".$obj_currency->sign."\" name=\"currency_code\" />
		<div id=\"order_summery\">
			<ul class=\"order_method\">
				<li>
					<h4>SHIPPING ADDRESS</h4>
					<a class=\"edit iframe4\" name=\"shipping_edit\" title=\"edit shipping address\" href=\"address.html?is_return=validation&payment=".$_GET['method']."\">edit</a>
					<p>" . $objShippingAddr->firstname . " " . $objShippingAddr->lastname . ", <br />" . $street . (($objShippingAddr->country == 'cn') ? $arrCitys[$objShippingAddr->city] :  $objShippingAddr->city) . "<br />" . (($objShippingAddr->country == 'cn') ? $arrStates[$objShippingAddr->state] : $objShippingAddr->state) . "&nbsp;" . (($objShippingAddr->postcode) ? $objShippingAddr->postcode . "&nbsp;" : "") . $countries[$objShippingAddr->country] . "</p>
				</li>
				<li>
					<h4>SHIPPING METHOD</h4>
					<a class=\"edit iframe4\" name=\"shipping_edit\" title=\"edit shipping address\" href=\"address.html?is_return=validation&payment=".$_GET['method']."\">edit</a>
					<p>".$obj_select_shipping->name."</p>
					" . $obj_select_shipping->ship_des . 
				"</li>
				<li>
					<h4>PAYMENT METHOD</h4>
					<a class=\"edit iframe4\" name=\"shipping_edit\" title=\"edit shipping address\" href=\"payment.html?step=2&is_return=validation\">edit</a>
					<p>COD</p>
				</li>
			</ul> <!-- order_method end -->";		
				
		$strHtml .= $str_category_Html;
			
		// generate the discount amount.
		$cnt = $this->get_shipping_cart_cnt($_SESSION['cart']);
		$_SESSION['ORDER']['shipping'] = $this->get_shipping_fee($_SESSION['cart'], $id_area, $shipping_pid, $arr_shippings[$id_carrier], $cnt);
		$total_amount = $_SESSION['ORDER']['totalPrice'] + $_SESSION['ORDER']['shipping'];
		$this->discount_total($_SESSION['ORDER']['totalPrice'], $discount, $is_fee_shipping, $is_voucher_exist);
		
		if (floatval($_SESSION['ORDER']['totalPrice'] + $_SESSION['ORDER']['shipping'] - $discount) < 0){
			$discount = $_SESSION['ORDER']['totalPrice'] + $_SESSION['ORDER']['shipping'];
		}
		$strHtml .= "<div id=\"checkout_total\"><div class=\"count_price\">
			<p>SUBTOTAL: <span>" . $this->obj_currency->change_order($_SESSION['ORDER']['totalPrice'],$_COOKIE['PAY_CURRENCY']) . "</span></p>
			<p>SHIPPING: <span id='total_shipping'>" . $this->obj_currency->change_order($_SESSION['ORDER']['shipping'],$_COOKIE['PAY_CURRENCY']) . "</span></p>
			<p class=\"order_givevoucher\"" . (($discount == 0.00) ? " style=\"display:none\"" : "") . ">GIFT VOUCHER: <span>- " . $this->obj_currency->change_order($discount,$_COOKIE['PAY_CURRENCY']) . "</span></p>
		</div> <!-- order_price end -->
		<div class=\"total_price\">
			<small>TOTAL //</small>
			<span><span id=\"total_cost\">" . $this->obj_currency->change_order(number_format(floatval($_SESSION['ORDER']['totalPrice'] + $_SESSION['ORDER']['shipping'] - $discount), 2, '.', ''),$_COOKIE['PAY_CURRENCY']) . "</span><input type='hidden' value='" . $_SESSION['ORDER']['shipping'] . "' /></span>
		</div> <!-- total_price end --></div>";	
		
		// javascript
		$strHtml .= '<input type="hidden" name="id_carrier" value="' . $id_carrier . '" />
			<script type="text/javascript">
				jQuery(function(){
					jQuery("input[@name=\'id_carrier\']").val("' . $id_carrier . '");
					$("input[@name=shipping]").each(function(value, el){
						$(el).removeAttr("checked");
						if ($(el).attr("ship_id") == "' . $id_carrier . '")
						{
							$(el).attr("checked", "checked");
						}
					});
					jQuery("#shipping_area").click(function(e){
						var el = e.target || e, total_cost = 0, org_shipping = 0;
						
						if (el.name != "undefined" && el.name == "shipping")
						{
							var _currency_code = jQuery("input[@name=\'currency_code\']").val();
							jQuery(".count_price #total_shipping").html(_currency_code + el.value);
							total_cost = parseFloat(jQuery(".total_price #total_cost").html());	
							org_shipping = parseFloat(jQuery(".total_price #total_cost").parent("span").find("input[@type=\'hidden\']").val());
							total_cost = total_cost - org_shipping + parseFloat(el.value);
							jQuery(".total_price input[@type=hidden]").val(el.value);
							jQuery(".total_price #total_cost").html(total_cost.toFixed(2));
							
							jQuery("input[@name=\'id_carrier\']").val($("input[@name=shipping][@checked]").parent("td").find("input[@type=hidden]").val());
							
							' . (($is_fee_shipping) ? '
							$.ajax({
								type:"POST",
								url:"validation.html?action=ajax_shipping",
								data:"shipping_id="+$("input[@name=shipping][@checked]").attr("ship_id")+"&amount=' .$total_amount . '",
								success:function(msg){
									if (msg != undefined) $("#checkout_total").html(msg);
								}
							});' : '') . '
						}
					});
					
					/*jQuery("#odr_submit").click(function(e){
						var el = jQuery(e.target) || jQuery(e);
						el.attr("disabled","disabled");
					});*/
				})
			</script>
		';
			
		$strHtml .= "<div class=\"submits_box\">
			<!-- Any comments -->
			<div class=\"any_comments\" style=\"float:right;margin:10px 0;\">
				<label><strong>ANY COMMENT OR SPECIAL REQUEST?</strong></label>
				<textarea name=\"odr_comments\" class=\"comments\" rows=\"5\" cols=\"50\" onfocus=\"if (this.value == '') {this.value = '';}\" onblur=\"if (this.value == ''){this.value = 'FOR EXAMPLE: PLEASE DELIVER BETWEEN 7 AND 9PM IN THE EVENING'; }\" style=\"color:#989898;\">FOR EXAMPLE: PLEASE DELIVER BETWEEN 7 AND 9PM IN THE EVENING</textarea>
			</div>
			<!-- comments end -->
			<p class=\"submits\"><a class=\"button_large\" href=\"".$this->Environment->base."shoppingcart.html\">Continue Shopping</a><input id=\"odr_submit\" class=\"submit\" type=\"submit\" value=\"" . ((!$is_noneStock && !$is_overStock) ? "CONFIRM ORDER" : "CONFIRM ORDER") . "\"/></p>
		</div>
		" . ((!$is_noneStock && !$is_overStock) ? "" : "<div class=\"error\">One or more item(s) is out of stock. Please update your shopping cart. We are sorry for the inconvenience. <a href=\"job-opportunities.html\" title=\"Contact us\">Contact us</a> for further assistance.
</div>") . "
		</div>" . ((isset($_SESSION['ORDER']['is_paypal_fast']) && $_SESSION['ORDER']['is_paypal_fast']) ? "<input type=\"hidden\" name=\"is_paypal_fast\" value=\"1\" />" : "") . (($discount != '0.00') ? "
		<input type=\"hidden\" name=\"vourcher\" class=\"text\" value=\"" . $this->Input->post('vourcher') . "\" />" : "") . "
		</form>
		<form id=\"gift_code\" method=\"post\" action=\"".$this->Environment->base."validation.html?method=COD&voucher=1\">
		<p><label>I HAVE A GIFT VOUCHER:</label> <input type=\"text\" name=\"vourcher\" class=\"text\" value=\"enter you code here\" onfocus=\"if (this.value == 'enter you code here') {this.value = '';}\" onblur=\"if (this.value == ''){this.value = 'enter you code here'; }\" /><input type=\"submit\" name=\"submit\" class=\"submit\" value=\"Submit\" />
		</p>
		" . (($this->Input->post("vourcher") && !$is_voucher_exist) ? "<div class=\"error\">Invalid code.Please try again or email <a href=\"mailto:support@daftshopping.com\">support@daftshopping.com</a> for assistance. We will get back to you asap.</div></form>" : "</form>");
		
		return $strHtml;
	}
	
	/**
	 * Generate and judge validation cod payment, and generate cod.
	 * @params float discount value
	 * @Return null
	 */
	public function generatePaypal($discount = 0.00, $is_voucher_exist=false)
	{
		$countries = array();
		$this->import("Database");
		$this->loadLanguageFile('countries');
		include(TL_ROOT . '/system/config/countries.php');
		
		// Get the shiping address.
		$objShippingAddr = $this->Database->prepare("SELECT * FROM tl_address_book WHERE id=?")
											->execute($_SESSION['ORDER']['address_shipping']);
		if ($objShippingAddr->numRows < 1)
			return;
		
		// Get the states.
		$arrStates = array();
		$objStates = $this->Database->prepare("SELECT * FROM `china_province` ORDER BY `province_en`")
									->execute(time());
		
		while ($objStates->next())
		{
			$arrStates[$objStates->id] = stripslashes($objStates->province_en);
		}
		
		// Get State.
		$arrCitys = array();			
		$objCitys = $this->Database->prepare("SELECT * FROM `china_city` ORDER BY `city_en`")
									->execute(time());
		
		while ($objCitys->next())
		{
			$arrCitys[$objCitys->id] = stripslashes($objCitys->city_en);
		}
									
		if($objShippingAddr->street_2=="line 2" || $objShippingAddr->street_2=="Address line 2") {
			$street = $objShippingAddr->street . ", ";
		}else{
			$street = $objShippingAddr->street . ", <br />" .$objShippingAddr->street_2;
		}
		
		/** purchase the category information and shipping information **/
		$arrCatalog = $_SESSION['cart'];
		$shipping_pid = 0;
		$bigger_catalog_price = 0;
		foreach ($arrCatalog as $key=>$arrCatalogInfo)
		{				
			if ($key == 'sessionID')
				continue;
				
			$catalogStock = 0;
			$is_noneStock = false;
			$is_overStock = false;
			
			// Judge the update information
			if ($this->Input->get('generateOrder'))
			{
				switch ($this->Input->get('generateOrder'))
				{
					case 'success':
						break;
					case 'failure':
						if (!$this->Input->get('stock'))
						{
							if ($arrCatalogInfo['id'] == $this->Input->get('id_catalog'))
								$is_noneStock = true;
						}
						else
							if ($arrCatalogInfo['id'] == $this->Input->get('id_catalog'))
								$is_overStock = true;
						break;
					default:
						break;
				}
			}
			// Get the stock of this catalog.
			$catalogStock = $this->getCurrentStockInfo($arrCatalogInfo['id'], $arrCatalogInfo['colour'], $arrCatalogInfo['size']);
			
			// Stock information deal with.
			if (is_null($catalogStock))
			{
				continue;
			}
			elseif (!$catalogStock)
			{
				$is_noneStock = true;
			}
			else 
			{
				$is_noneStock = false;
				if (intval($arrCatalogInfo['quantity']) > $catalogStock)
				{
					$_SESSION['cart'][$key]['quantity'] = $catalogStock;
					$is_overStock = true;
				}
				else 
					$is_overStock = false;
			}
			
			// Get catalog size.
			$objCatalogSize = $this->Database->prepare("SELECT * FROM catalog_size WHERE id=?")
											->execute($arrCatalogInfo['size']);
			$objCurrentCatalog = $this->Database->prepare("SELECT * FROM product_catalog WHERE id=?")
											->execute($arrCatalogInfo['id']);
			$objCataColor = $this->Database->prepare("SELECT `id` FROM `catalog_colour` WHERE `title`=?")
											->execute($arrCatalogInfo['colour']);
											
			$imgPath = "daft_files/catalog/products/" . $arrCatalogInfo['skuid'] . "/" . $arrCatalogInfo['colour'] . "/1.jpg";
			
			$str_category_Html .= "<div class=\"error\"" . ((!$is_noneStock) ? ' style="display:none;"' : '') . ">The quantity of this product is out of stock. Please select again.</div>
						<div class=\"error\"" . ((!$is_overStock) ? ' style="display:none;"' : '') . ">The quantity of current product has overd the stock. Please select another product.</div>
				<table class=\"cart_item\">
				<tr>
					<td rowspan=\"2\" class=\"td_pic\"><a href=\"./product.html?category=".$objCurrentCatalog->category."&id=". $objCurrentCatalog->id . "&id_colour=" . $objCataColor->id . "&id_size=" . $arrCatalogInfo['size'] . "\" target=\"_blank\"><img src=\"image.php?src=" . $imgPath . "&width=79&height=79\" alt=\"\" /></a></td>
					<td class=\"td_info\">
						<h4><a href=\"./product.html?category=".$objCurrentCatalog->category."&id=". $objCurrentCatalog->id . "&id_colour=" . $objCataColor->id . "&id_size=" . $arrCatalogInfo['size'] . "\" target=\"_blank\">" . $arrCatalogInfo['name'] . "</a></h4>
						<small>SKU #" . $arrCatalogInfo['skuid'] . "</small><br />
						<small>" . $this->obj_currency->change_order($arrCatalogInfo['price'],$_COOKIE['PAY_CURRENCY'])  . "</small>" . (($arrCatalogInfo['gift_wrapping']) ? "<br /><small>GIFT WRAPPING "
						 . $this->obj_currency->change_order(number_format(floatval($arrCatalogInfo['gwPrice']), 2, '.', ''),$_COOKIE['PAY_CURRENCY']) . "</small>" : "") . "
					</td>
					<td rowspan=\"2\" class=\"td_skin\">
						<div class=\"skin\">
							<p>
								<label>COLOR</label>
								<span class=\"skin_value\">" . $arrCatalogInfo['colour'] . "</span>
							</p>
							<p>
								<label>SIZE</label>
								<span class=\"skin_value\">" . $objCatalogSize->size . "</span>
							</p>
							<p>
								<label>QUANTITY</label>
								" . ((!$is_noneStock) ? ("
								<span class=\"skin_value\">" . $arrCatalogInfo['quantity'] . "</span>") : "<span class=\"error\">Out of stock - Please remove from your cart.</span>") . "
							</p>
						</div>
					</td>
					<td rowspan=\"2\" class=\"unit_price\"><strong>" . $this->obj_currency->change_order(number_format(floatval($arrCatalogInfo['price']) * floatval($arrCatalogInfo['quantity'])+$arrCatalogInfo['gwPrice'], 2, '.', ''),$_COOKIE['PAY_CURRENCY'])  . "</strong></td>
				</tr> 
			</table>";
			
			if ($arrCatalogInfo['price'] > $bigger_catalog_price)
			{
				$shipping_pid = $objCurrentCatalog->id;
				$bigger_catalog_price = $arrCatalogInfo['price'];
			}
		}
		
		$str_category_Html .= "<p class=\"cart_navigation\"></p>";
		
		// generate shipping method.
		// Get shipping area
		$obj_catalogs = $this->Database->prepare("SELECT * FROM product_catalog WHERE id=?")
											->execute($shipping_pid,time(),time());
		if (!$obj_catalogs->programe)
		{
			$obj_programmes = $this->Database->prepare("SELECT * FROM tl_programmes WHERE is_default='true'")
											->execute(time(),time());
			$obj_catalogs->programe = $obj_programmes->id;
		}
		$id_area = 0;
		$obj_shipping_area = $this->Database->prepare("SELECT area.`id` 
														FROM tl_areas AS area 
														INNER JOIN tl_countries AS country ON country.id_area = area.id 
														WHERE country.name=?")
											->execute($objShippingAddr->country);
		if ($obj_shipping_area->numRows > 0)
		{
			$id_area = $obj_shipping_area->id;
		}
		
		// generate shipping method.
		if ($id_area)
		{
			$objShippings = $this->Database->prepare("SELECT * FROM tl_shippings WHERE area=? AND pid=? ORDER BY sort,name")
										->execute($id_area, $obj_catalogs->programe, time(), time());
			if ($objShippings->numRows > 0)
			{
				while ($objShippings->next())
				{
					$arr_id_shppings[] = $objShippings->id;
					$arr_shippings[$objShippings->id] = array(
						'id'=>$objShippings->id,
						'firstprice'=>$objShippings->firstprice,
						'continueprice'=>$objShippings->continueprice,
					);
				}
				if (!in_array((int)$_SESSION['ORDER']['id_carrier'], $arr_id_shppings))
				{
					$_SESSION['ORDER']['id_carrier'] = $arr_id_shppings[0];
				}
			}
		}
		$objShippings = $this->Database->prepare("SELECT * FROM tl_shippings WHERE pid=? ORDER BY sort,name")
										->execute($obj_catalogs->programe, time(), time());
		if (isset($_SESSION['ORDER']['id_carrier']) && $_SESSION['ORDER']['id_carrier'])
			$id_carrier = $_SESSION['ORDER']['id_carrier'];
		
		if ($objShippings->numRows >= 1)
		{
			/*$str_category_Html .= '<div id="shipping_area"><table><tbody>';
			$index = 0;
			while($objShippings->next())
			{
				if (!$id_carrier)
					$id_carrier = $objShippings->id;
				
				if ($id_area && $objShippings->area != $id_area)
					continue;
					
				$cnt = $this->get_shipping_cart_cnt($_SESSION['cart']);
				$shipping_fee = $this->get_shipping_fee($objShippings->firstprice, $objShippings->continueprice, $cnt);
				$shipping_fee = number_format($shipping_fee, 2, '.', '');
				
				$str_category_Html .= '<tr>
										<td class="td1"><input type="radio" ship_id="' . $objShippings->id . '" id="shipping_' . $objShippings->id . '" name="shipping" class="radio" value="' . $shipping_fee . '"' . (($index == 0 || $_SESSION['ORDER']['id_carrier'] == $objShippings->id) ? ' checked="checked"' : '') . ' /><input type="hidden" value="' . $objShippings->id . '" /></td>
										<td class="td2">' . $objShippings->name . '&nbsp;' . $objShippings->des . '</td>
									</tr>';
									
				$index++;
			}
			$str_category_Html .= '</tbody></table></div>';*/
		}
		/** end **/
		
		$obj_select_shipping = $this->Database->prepare("SELECT * FROM `tl_shippings` WHERE `id`=?")
											->execute($id_carrier);
		$obj_currency = $this->Database->prepare("SELECT * FROM `tl_currency` WHERE `is_default`=1")
										->execute(time());
		
		$ec_paypal_disabled = ($_SESSION['ORDER']['is_paypal_fast']) ? ' style="display:none;"' : '';
		$strHtml = "<form id=\"validate_form\" method=\"post\" action=\"".$this->Environment->base."validation.html?method=Paypal\">
		<input type=\"hidden\" value=\"1\" name=\"confirm\"/>
		<input type=\"hidden\" value=\"".$obj_currency->sign."\" name=\"currency_code\" />
		<div id=\"order_summery\">
			<ul class=\"order_method\">
				<li>
					<h4>SHIPPING ADDRESS</h4>
					<a class=\"edit iframe4\" name=\"shipping_edit\" title=\"edit shipping address\" href=\"address.html?is_return=validation&payment=".$_GET['method']."\">edit</a>
					<p>" . $objShippingAddr->firstname . " " . $objShippingAddr->lastname . ", <br />" . $street . (($objShippingAddr->country == 'cn') ? $arrCitys[$objShippingAddr->city] :  $objShippingAddr->city) . "<br />" . (($objShippingAddr->country == 'cn') ? $arrStates[$objShippingAddr->state] : $objShippingAddr->state) . "&nbsp;" . (($objShippingAddr->postcode) ? $objShippingAddr->postcode . "&nbsp;" : "") . $countries[$objShippingAddr->country] . "</p>
				</li>
				<li>
					<h4>SHIPPING METHOD</h4>
					<a class=\"edit iframe4\" name=\"shipping_edit\" title=\"edit shipping address\" href=\"address.html?is_return=validation&payment=".$_GET['method']."\">edit</a>
					<p>".$obj_select_shipping->name."</p>
					" . $obj_select_shipping->ship_des . 
				"</li>
				<li>
					<h4>PAYMENT METHOD</h4>
					<a class=\"edit iframe4\" name=\"shipping_edit\" title=\"edit shipping address\"".$ec_paypal_disabled." href=\"payment.html?step=2&is_return=validation\">edit</a>
					<p>Paypal International</p>
				</li>
			</ul> <!-- order_method end -->";		
				
		$strHtml .= $str_category_Html;
			
		// generate the discount amount.
		$cnt = $this->get_shipping_cart_cnt($_SESSION['cart']);
		$_SESSION['ORDER']['shipping'] = $this->get_shipping_fee($_SESSION['cart'], $id_area, $shipping_pid, $arr_shippings[$id_carrier], $cnt);
		$total_amount = $_SESSION['ORDER']['totalPrice'] + $_SESSION['ORDER']['shipping'];
		$this->discount_total($_SESSION['ORDER']['totalPrice'], $discount, $is_fee_shipping, $is_voucher_exist);
		
		if (floatval($_SESSION['ORDER']['totalPrice'] + $_SESSION['ORDER']['shipping'] - $discount) < 0){
			$discount = $_SESSION['ORDER']['totalPrice'] + $_SESSION['ORDER']['shipping'];
		}
		$strHtml .= "<div id=\"checkout_total\"><div class=\"count_price\">
			<p>SUBTOTAL: <span>" . $this->obj_currency->change_order($_SESSION['ORDER']['totalPrice'],$_COOKIE['PAY_CURRENCY']) . "</span></p>
			<p>SHIPPING: <span id='total_shipping'>" . $this->obj_currency->change_order(number_format(floatval($_SESSION['ORDER']['shipping']), 2, '.', ''),$_COOKIE['PAY_CURRENCY']) . "</span></p>
			<p class=\"order_givevoucher\"" . (($discount == 0.00) ? " style=\"display:none\"" : "") . ">GIFT VOUCHER: <span>- " . $this->obj_currency->change_order(number_format(floatval($discount), 2, '.', ''),$_COOKIE['PAY_CURRENCY']) . "</span></p>
		</div> <!-- order_price end -->
		<div class=\"total_price\">
			<small>TOTAL //</small>
			<span><span id=\"total_cost\">" . $this->obj_currency->change_order(number_format(floatval($_SESSION['ORDER']['totalPrice'] + $_SESSION['ORDER']['shipping'] - $discount), 2, '.', ''),$_COOKIE['PAY_CURRENCY']) . "</span><input type='hidden' value='" . $_SESSION['ORDER']['shipping'] . "' /></span>
		</div> <!-- total_price end --></div>";	
		
		// javascript
		$strHtml .= '<input type="hidden" name="id_carrier" value="' . $id_carrier . '" />
			<script type="text/javascript">
				jQuery(function(){
					jQuery("input[@name=\'id_carrier\']").val("' . $id_carrier . '");
					$("input[@name=shipping]").each(function(value, el){
						$(el).removeAttr("checked");
						if ($(el).attr("ship_id") == "' . $id_carrier . '")
						{
							$(el).attr("checked", "checked");
						}
					});
					jQuery("#shipping_area").click(function(e){
						var el = e.target || e, total_cost = 0, org_shipping = 0;
						
						if (el.name != "undefined" && el.name == "shipping")
						{
							var _currency_code = jQuery("input[@name=\'currency_code\']").val();
							jQuery(".count_price #total_shipping").html(_currency_code + el.value);
							total_cost = parseFloat(jQuery(".total_price #total_cost").html());	
							org_shipping = parseFloat(jQuery(".total_price #total_cost").parent("span").find("input[@type=\'hidden\']").val());
							total_cost = total_cost - org_shipping + parseFloat(el.value);
							jQuery(".total_price input[@type=hidden]").val(el.value);
							jQuery(".total_price #total_cost").html(total_cost.toFixed(2));
							
							jQuery("input[@name=\'id_carrier\']").val($("input[@name=shipping][@checked]").parent("td").find("input[@type=hidden]").val());
							
							' . (($is_fee_shipping) ? '
							$.ajax({
								type:"POST",
								url:"validation.html?action=ajax_shipping",
								data:"shipping_id="+$("input[@name=shipping][@checked]").attr("ship_id")+"&amount=' .$total_amount . '",
								success:function(msg){
									if (msg != undefined) $("#checkout_total").html(msg);
								}
							});' : '') . '
						}
					});
				})
			</script>
		';
	
		$strHtml .= "<div class=\"submits_box\">
			<!-- Any comments -->
			<div class=\"any_comments\" style=\"float:right;margin:10px 0;\">
				<label><strong>ANY COMMENT OR SPECIAL REQUEST?</strong></label>
				<textarea name=\"odr_comments\" class=\"comments\" rows=\"5\" cols=\"50\" onfocus=\"if (this.value == '') {this.value = '';}\" onblur=\"if (this.value == ''){this.value = 'FOR EXAMPLE: PLEASE DELIVER BETWEEN 7 AND 9PM IN THE EVENING'; }\" style=\"color:#989898;\">FOR EXAMPLE: PLEASE DELIVER BETWEEN 7 AND 9PM IN THE EVENING</textarea>
			</div>
			<!-- comments end -->
			<p class=\"submits\"><a class=\"button_large\" href=\"".$this->Environment->base."shoppingcart.html\">Continue Shopping</a><input id=\"odr_submit\" class=\"submit\" type=\"submit\" value=\"" . ((!$is_noneStock && !$is_overStock) ? "CONFIRM ORDER" : "CONFIRM ORDER") . "\" name=\"submit\"/></p>
		</div>
		" . ((!$is_noneStock && !$is_overStock) ? "" : "<div class=\"error\">One or more item(s) is out of stock. Please update your shopping cart. We are sorry for the inconvenience. <a href=\"job-opportunities.html\" title=\"Contact us\">Contact us</a> for further assistance.
</div>") . "
		</div>" . ((isset($_SESSION['ORDER']['is_paypal_fast']) && $_SESSION['ORDER']['is_paypal_fast']) ? "<input type=\"hidden\" name=\"is_paypal_fast\" value=\"1\" />" : "") . (($discount != '0.00') ? "
		<input type=\"hidden\" name=\"vourcher\" class=\"text\" value=\"" . $this->Input->post('vourcher') . "\" />" : "") . "
		</form>
		<form id=\"gift_code\" method=\"post\" action=\"".$this->Environment->base."validation.html?method=Paypal&voucher=1\">
		<p><label>I HAVE A GIFT VOUCHER:</label> <input type=\"text\" name=\"vourcher\" class=\"text\" value=\"enter you code here\" onfocus=\"if (this.value == 'enter you code here') {this.value = '';}\" onblur=\"if (this.value == ''){this.value = 'enter you code here'; }\" /><input type=\"submit\" name=\"submit\" class=\"submit\" value=\"Submit\" />
		</p>
		" . (($this->Input->post("vourcher") && !$is_voucher_exist) ? "<div class=\"error\">Invalid code.Please try again or email <a href=\"mailto:support@daftshopping.com\">support@daftshopping.com</a> for assistance. We will get back to you asap.</div></form>" : "</form>");
		
		return $strHtml;
	}
	
	/**
	 * Generate and judge validation cod payment, and generate cod.
	 * @params float discount value
	 * @Return null
	 */
	public function generateAlipay($discount = 0.00, $is_voucher_exist=false)
	{
		$countries = array();
		$this->import("Database");
		$this->loadLanguageFile('countries');
		include(TL_ROOT . '/system/config/countries.php');
		
		// Get the shiping address.
		$objShippingAddr = $this->Database->prepare("SELECT * FROM tl_address_book WHERE id=?")
											->execute($_SESSION['ORDER']['address_shipping']);
		if ($objShippingAddr->numRows < 1)
			return;
		
		// Get the states.
		$arrStates = array();
		$objStates = $this->Database->prepare("SELECT * FROM `china_province` ORDER BY `province_en`")
									->execute(time());
		
		while ($objStates->next())
		{
			$arrStates[$objStates->id] = stripslashes($objStates->province_en);
		}
		
		// Get State.
		$arrCitys = array();			
		$objCitys = $this->Database->prepare("SELECT * FROM `china_city` ORDER BY `city_en`")
									->execute(time());
		
		while ($objCitys->next())
		{
			$arrCitys[$objCitys->id] = stripslashes($objCitys->city_en);
		}
									
		if($objShippingAddr->street_2=="line 2" || $objShippingAddr->street_2=="Address line 2") {
			$street = $objShippingAddr->street . ", ";
		}else{
			$street = $objShippingAddr->street . ", <br />" .$objShippingAddr->street_2;
		}
		
		/** purchase the category information and shipping information **/
		$arrCatalog = $_SESSION['cart'];
		$shipping_pid = 0;
		$bigger_catalog_price = 0;
		foreach ($arrCatalog as $key=>$arrCatalogInfo)
		{				
			if ($key == 'sessionID')
				continue;
				
			$catalogStock = 0;
			$is_noneStock = false;
			$is_overStock = false;
			
			// Judge the update information
			if ($this->Input->get('generateOrder'))
			{
				switch ($this->Input->get('generateOrder'))
				{
					case 'success':
						break;
					case 'failure':
						if (!$this->Input->get('stock'))
						{
							if ($arrCatalogInfo['id'] == $this->Input->get('id_catalog'))
								$is_noneStock = true;
						}
						else
							if ($arrCatalogInfo['id'] == $this->Input->get('id_catalog'))
								$is_overStock = true;
						break;
					default:
						break;
				}
			}
			// Get the stock of this catalog.
			$catalogStock = $this->getCurrentStockInfo($arrCatalogInfo['id'], $arrCatalogInfo['colour'], $arrCatalogInfo['size']);
			
			// Stock information deal with.
			if (is_null($catalogStock))
			{
				continue;
			}
			elseif (!$catalogStock)
			{
				$is_noneStock = true;
			}
			else 
			{
				$is_noneStock = false;
				if (intval($arrCatalogInfo['quantity']) > $catalogStock)
				{
					$_SESSION['cart'][$key]['quantity'] = $catalogStock;
					$is_overStock = true;
				}
				else 
					$is_overStock = false;
			}
			// Get catalog size.
			$objCatalogSize = $this->Database->prepare("SELECT * FROM catalog_size WHERE id=?")
											->execute($arrCatalogInfo['size']);
			$objCurrentCatalog = $this->Database->prepare("SELECT * FROM product_catalog WHERE id=?")
											->execute($arrCatalogInfo['id']);
			$objCataColor = $this->Database->prepare("SELECT `id` FROM `catalog_colour` WHERE `title`=?")
											->execute($arrCatalogInfo['colour']);
											
			$imgPath = "daft_files/catalog/products/" . $arrCatalogInfo['skuid'] . "/" . $arrCatalogInfo['colour'] . "/1.jpg";
			
			$str_category_Html .= "<div class=\"error\"" . ((!$is_noneStock) ? ' style="display:none;"' : '') . ">The quantity of this product is out of stock. Please select again.</div>
						<div class=\"error\"" . ((!$is_overStock) ? ' style="display:none;"' : '') . ">The quantity of current product has overd the stock. Please select another product.</div>
				<table class=\"cart_item\">
				<tr>
					<td rowspan=\"2\" class=\"td_pic\"><a href=\"./product.html?category=".$objCurrentCatalog->category."&id=". $objCurrentCatalog->id . "&id_colour=" . $objCataColor->id . "&id_size=" . $arrCatalogInfo['size'] . "\" target=\"_blank\"><img src=\"image.php?src=" . $imgPath . "&width=79&height=79\" alt=\"\" /></a></td>
					<td class=\"td_info\">
						<h4><a href=\"./product.html?category=".$objCurrentCatalog->category."&id=". $objCurrentCatalog->id . "&id_colour=" . $objCataColor->id . "&id_size=" . $arrCatalogInfo['size'] . "\" target=\"_blank\">" . $arrCatalogInfo['name'] . "</a></h4>
						<small>SKU #" . $arrCatalogInfo['skuid'] . "</small><br />
						<small>" . $this->obj_currency->change_order($arrCatalogInfo['price'],$_COOKIE['PAY_CURRENCY'])  . "</small>" . (($arrCatalogInfo['gift_wrapping']) ? "<br /><small>GIFT WRAPPING "
						 . $this->obj_currency->change_order(number_format(floatval($arrCatalogInfo['gwPrice']), 2, '.', ''),$_COOKIE['PAY_CURRENCY']) . "</small>" : "") . "
					</td>
					<td rowspan=\"2\" class=\"td_skin\">
						<div class=\"skin\">
							<p>
								<label>COLOR</label>
								<span class=\"skin_value\">" . $arrCatalogInfo['colour'] . "</span>
							</p>
							<p>
								<label>SIZE</label>
								<span class=\"skin_value\">" . $objCatalogSize->size . "</span>
							</p>
							<p>
								<label>QUANTITY</label>
								" . ((!$is_noneStock) ? ("
								<span class=\"skin_value\">" . $arrCatalogInfo['quantity'] . "</span>") : "<span class=\"error\">Out of stock - Please remove from your cart.</span>") . "
							</p>
						</div>
					</td>
					<td rowspan=\"2\" class=\"unit_price\"><strong>" . $this->obj_currency->change_order(number_format(floatval($arrCatalogInfo['price']) * floatval($arrCatalogInfo['quantity'])+$arrCatalogInfo['gwPrice'], 2, '.', ''),$_COOKIE['PAY_CURRENCY'])  . "</strong></td>
				</tr> 
			</table>";
			
			if ($arrCatalogInfo['price'] > $bigger_catalog_price)
			{
				$shipping_pid = $objCurrentCatalog->id;
				$bigger_catalog_price = $arrCatalogInfo['price'];
			}
		}
		
		$str_category_Html .= "<p class=\"cart_navigation\"></p>";
		
		// generate shipping method.
		// Get shipping area
		$obj_catalogs = $this->Database->prepare("SELECT * FROM product_catalog WHERE id=?")
											->execute($shipping_pid,time(),time());
		if (!$obj_catalogs->programe)
		{
			$obj_programmes = $this->Database->prepare("SELECT * FROM tl_programmes WHERE is_default='true'")
											->execute(time(),time());
			$obj_catalogs->programe = $obj_programmes->id;
		}
		$id_area = 0;
		$obj_shipping_area = $this->Database->prepare("SELECT area.`id` 
														FROM tl_areas AS area 
														INNER JOIN tl_countries AS country ON country.id_area = area.id 
														WHERE country.name=?")
											->execute($objShippingAddr->country);
		if ($obj_shipping_area->numRows > 0)
		{
			$id_area = $obj_shipping_area->id;
		}
		
		// generate shipping method.
		if ($id_area)
		{
			$objShippings = $this->Database->prepare("SELECT * FROM tl_shippings WHERE area=? AND pid=? ORDER BY sort,name")
										->execute($id_area, $obj_catalogs->programe, time(), time());
			if ($objShippings->numRows > 0)
			{
				while ($objShippings->next())
				{
					$arr_id_shppings[] = $objShippings->id;
					$arr_shippings[$objShippings->id] = array(
						'id'=>$objShippings->id,
						'firstprice'=>$objShippings->firstprice,
						'continueprice'=>$objShippings->continueprice,
					);
				}
				if (!in_array((int)$_SESSION['ORDER']['id_carrier'], $arr_id_shppings))
				{
					$_SESSION['ORDER']['id_carrier'] = $arr_id_shppings[0];
				}
			}
		}
		$objShippings = $this->Database->prepare("SELECT * FROM tl_shippings WHERE pid=? ORDER BY sort,name")
										->execute($obj_catalogs->programe, time(), time());
		if (isset($_SESSION['ORDER']['id_carrier']) && $_SESSION['ORDER']['id_carrier'])
			$id_carrier = $_SESSION['ORDER']['id_carrier'];
		
		if ($objShippings->numRows >= 1)
		{
			/*$str_category_Html .= '<div id="shipping_area"><table><tbody>';
			$index = 0;
			while($objShippings->next())
			{
				if (!$id_carrier)
					$id_carrier = $objShippings->id;
				
				if ($id_area && $objShippings->area != $id_area)
					continue;
					
				$cnt = $this->get_shipping_cart_cnt($_SESSION['cart']);
				$shipping_fee = $this->get_shipping_fee($objShippings->firstprice, $objShippings->continueprice, $cnt);
				$shipping_fee = number_format($shipping_fee, 2, '.', '');
				
				$str_category_Html .= '<tr>
										<td class="td1"><input type="radio" ship_id="' . $objShippings->id . '" id="shipping_' . $objShippings->id . '" name="shipping" class="radio" value="' . $shipping_fee . '"' . (($index == 0 || $_SESSION['ORDER']['id_carrier'] == $objShippings->id) ? ' checked="checked"' : '') . ' /><input type="hidden" value="' . $objShippings->id . '" /></td>
										<td class="td2">' . $objShippings->name . '&nbsp;' . $objShippings->des . '</td>
									</tr>';
									
				$index++;
			}
			$str_category_Html .= '</tbody></table></div>';*/
		}
		/** end **/
		
		$obj_select_shipping = $this->Database->prepare("SELECT * FROM `tl_shippings` WHERE `id`=?")
											->execute($id_carrier);
		$obj_currency = $this->Database->prepare("SELECT * FROM `tl_currency` WHERE `is_default`=1")
										->execute(time());
											
		$strHtml = "<form id=\"validate_form\" method=\"post\" action=\"".$this->Environment->base."validation.html?method=Alipay\">
		<input type=\"hidden\" value=\"1\" name=\"confirm\"/>
		<input type=\"hidden\" value=\"".$obj_currency->sign."\" name=\"currency_code\" />
		<div id=\"order_summery\">
			<ul class=\"order_method\">
				<li>
					<h4>SHIPPING ADDRESS</h4>
					<a class=\"edit iframe4\" name=\"shipping_edit\" title=\"edit shipping address\" href=\"address.html?is_return=validation&payment=".$_GET['method']."\">edit</a>
					<p>" . $objShippingAddr->firstname . " " . $objShippingAddr->lastname . ", <br />" . $street . (($objShippingAddr->country == 'cn') ? $arrCitys[$objShippingAddr->city] :  $objShippingAddr->city) . "<br />" . (($objShippingAddr->country == 'cn') ? $arrStates[$objShippingAddr->state] : $objShippingAddr->state) . "&nbsp;" . (($objShippingAddr->postcode) ? $objShippingAddr->postcode . "&nbsp;" : "") . $countries[$objShippingAddr->country] . "</p>
				</li>
				<li>
					<h4>SHIPPING METHOD</h4>
					<a class=\"edit iframe4\" name=\"shipping_edit\" title=\"edit shipping address\" href=\"address.html?is_return=validation&payment=".$_GET['method']."\">edit</a>
					<p><small>".$obj_select_shipping->name."</small></p>
					" . $obj_select_shipping->ship_des . 
				"</li>
				<li>
					<h4>PAYMENT METHOD</h4>
					<a class=\"edit iframe4\" name=\"shipping_edit\" title=\"edit shipping address\" href=\"payment.html?step=2&is_return=validation\">edit</a>
					<p>Alipay</p>
				</li>
			</ul> <!-- order_method end -->";		
				
		$strHtml .= $str_category_Html;
			
		// generate the discount amount.
		$cnt = $this->get_shipping_cart_cnt($_SESSION['cart']);
		$_SESSION['ORDER']['shipping'] = $this->get_shipping_fee($_SESSION['cart'], $id_area, $shipping_pid, $arr_shippings[$id_carrier], $cnt);		
		$total_amount = $_SESSION['ORDER']['totalPrice'] + $_SESSION['ORDER']['shipping'];
		$this->discount_total($_SESSION['ORDER']['totalPrice'], $discount, $is_fee_shipping, $is_voucher_exist);
		
		if (floatval($_SESSION['ORDER']['totalPrice'] + $_SESSION['ORDER']['shipping'] - $discount) < 0){
			$discount = $_SESSION['ORDER']['totalPrice'] + $_SESSION['ORDER']['shipping'];
		}
		$strHtml .= "<div id=\"checkout_total\"><div class=\"count_price\">
			<p>SUBTOTAL: <span>" . $this->obj_currency->change_order($_SESSION['ORDER']['totalPrice'],$_COOKIE['PAY_CURRENCY']) . "</span></p>
			<p>SHIPPING: <span id='total_shipping'>" . $this->obj_currency->change_order(number_format(floatval($_SESSION['ORDER']['shipping']), 2, '.', ''),$_COOKIE['PAY_CURRENCY']) . "</span></p>
			<p class=\"order_givevoucher\"" . (($discount == 0.00) ? " style=\"display:none\"" : "") . ">GIFT VOUCHER: <span>- " . $this->obj_currency->change_order(number_format(floatval($discount), 2, '.', ''),$_COOKIE['PAY_CURRENCY']) . "</span></p>
		</div> <!-- order_price end -->
		<div class=\"total_price\">
			<small>TOTAL //</small>
			<span><span id=\"total_cost\">" . $this->obj_currency->change_order(number_format(floatval($_SESSION['ORDER']['totalPrice'] + $_SESSION['ORDER']['shipping'] - $discount), 2, '.', ''),$_COOKIE['PAY_CURRENCY']) . "</span><input type='hidden' value='" . $_SESSION['ORDER']['shipping'] . "' /></span>
		</div> <!-- total_price end --></div>";	
		
		// javascript
		$strHtml .= '<input type="hidden" name="id_carrier" value="' . $id_carrier . '" />
			<script type="text/javascript">
				jQuery(function(){
					jQuery("input[@name=\'id_carrier\']").val("' . $id_carrier . '");
					$("input[@name=shipping]").each(function(value, el){
						$(el).removeAttr("checked");
						if ($(el).attr("ship_id") == "' . $id_carrier . '")
						{
							$(el).attr("checked", "checked");
						}
					});
					jQuery("#shipping_area").click(function(e){
						var el = e.target || e, total_cost = 0, org_shipping = 0;
						
						if (el.name != "undefined" && el.name == "shipping")
						{
							var _currency_code = jQuery("input[@name=\'currency_code\']").val();
							jQuery(".count_price #total_shipping").html(_currency_code + el.value);
							total_cost = parseFloat(jQuery(".total_price #total_cost").html());	
							org_shipping = parseFloat(jQuery(".total_price #total_cost").parent("span").find("input[@type=\'hidden\']").val());
							total_cost = total_cost - org_shipping + parseFloat(el.value);
							jQuery(".total_price input[@type=hidden]").val(el.value);
							jQuery(".total_price #total_cost").html(total_cost.toFixed(2));
							
							jQuery("input[@name=\'id_carrier\']").val($("input[@name=shipping][@checked]").parent("td").find("input[@type=hidden]").val());
							
							' . (($is_fee_shipping) ? '
							$.ajax({
								type:"POST",
								url:"validation.html?action=ajax_shipping",
								data:"shipping_id="+$("input[@name=shipping][@checked]").attr("ship_id")+"&amount=' .$total_amount . '",
								success:function(msg){
									if (msg != undefined) $("#checkout_total").html(msg);
								}
							});' : '') . '
						}
					});
				})
			</script>
		';
	
		$strHtml .= "<div class=\"submits_box\">
			<!-- Any comments -->
			<div class=\"any_comments\" style=\"float:right;margin:10px 0;\">
				<label><strong>ANY COMMENT OR SPECIAL REQUEST?</strong></label>
				<textarea name=\"odr_comments\" class=\"comments\" rows=\"5\" cols=\"50\" onfocus=\"if (this.value == '') {this.value = '';}\" onblur=\"if (this.value == ''){this.value = 'FOR EXAMPLE: PLEASE DELIVER BETWEEN 7 AND 9PM IN THE EVENING'; }\" style=\"color:#989898;\">FOR EXAMPLE: PLEASE DELIVER BETWEEN 7 AND 9PM IN THE EVENING</textarea>
			</div>
			<!-- comments end -->
			<p class=\"submits\"><a class=\"button_large\" href=\"".$this->Environment->base."shoppingcart.html\">Continue Shopping</a><input id=\"odr_submit\" class=\"submit\" type=\"submit\" value=\"" . ((!$is_noneStock && !$is_overStock) ? "CONFIRM ORDER" : "CONFIRM ORDER") . "\" name=\"submit\"/></p>
		</div>
		" . ((!$is_noneStock && !$is_overStock) ? "" : "<div class=\"error\">One or more item(s) is out of stock. Please update your shopping cart. We are sorry for the inconvenience. <a href=\"job-opportunities.html\" title=\"Contact us\">Contact us</a> for further assistance.
</div>") . "
		</div>" . ((isset($_SESSION['ORDER']['is_paypal_fast']) && $_SESSION['ORDER']['is_paypal_fast']) ? "<input type=\"hidden\" name=\"is_paypal_fast\" value=\"1\" />" : "") . (($discount != '0.00') ? "
		<input type=\"hidden\" name=\"vourcher\" class=\"text\" value=\"" . $this->Input->post('vourcher') . "\" />" : "") . "
		</form>
		<form id=\"gift_code\" method=\"post\" action=\"".$this->Environment->base."validation.html?method=Alipay&voucher=1\">
		<p><label>I HAVE A GIFT VOUCHER:</label> <input type=\"text\" name=\"vourcher\" class=\"text\" value=\"enter you code here\" onfocus=\"if (this.value == 'enter you code here') {this.value = '';}\" onblur=\"if (this.value == ''){this.value = 'enter you code here'; }\" /><input type=\"submit\" name=\"submit\" class=\"submit\" value=\"Submit\" />
		</p>
		" . (($this->Input->post("vourcher") && !$is_voucher_exist) ? "<div class=\"error\">Invalid code.Please try again or email <a href=\"mailto:support@daftshopping.com\">support@daftshopping.com</a> for assistance. We will get back to you asap.</div></form>" : "</form>");
		
		return $strHtml;
	}
	
	/**
	 * Generate the order.
	 * @params null
	 * @Return null
	 */
	public function generateOrder()
	{
		if (!isset($_GET) || !$_GET['method'])
			return;
		
		if (isset($_POST['shipping']) && $_POST['shipping'])
			$_SESSION['ORDER']['shipping'] = $_POST['shipping'];
		if (isset($_POST['id_carrier']) && $_POST['id_carrier'])
			$_SESSION['ORDER']['id_carrier'] = $_POST['id_carrier'];
		
		$this->import('Database');
		$arrCatalog = $_SESSION['cart'];
		foreach ($arrCatalog as $key=>$arrCatalogInfo)
		{				
			if ($key == 'sessionID')
				continue;
				
			$catalogStock = 0;
			$is_noneStock = false;
			$is_overStock = false;
			// Get the stock of this catalog.
			$catalogStock = $this->getCurrentStockInfo($arrCatalogInfo['id'], $arrCatalogInfo['colour'], $arrCatalogInfo['size']);
			
			// Stock information deal with.
			if (is_null($catalogStock))
			{
				$this->redirect($this->Environment->request . '&generateOrder=failure&id_catalog=' . $arrCatalogInfo['id']);
			}
			elseif (!$catalogStock)
			{
				$is_noneStock = true;
				$this->redirect($this->Environment->request . '&generateOrder=failure&id_catalog=' . $arrCatalogInfo['id'] . '&stock=0');
			}
			else 
			{
				$is_noneStock = false;
				if (intval($arrCatalogInfo['quantity']) > $catalogStock)
				{
					$_SESSION['cart']['quantity'] = $catalogStock;
					$is_overStock = true;
					$this->redirect($this->Environment->request . '&generateOrder=failure&id_catalog=' . $arrCatalogInfo['id'] . '&stock=' . $catalogStock);
				}
				else 
					$is_overStock = false;
			}
		}
		
		$arrCatalogs = array();
		$orderId = 0;
		$member_id = 0;
		$totalWrapping = 0;
		$insetId = 0;
		$id_orderNo = date('YmdHis');
		foreach ($_SESSION['cart'] as $key=>$arrCartInfo)
		{
			if ($key == 'sessionID')
				continue;
			$totalWrapping += (intval($arrCartInfo['gift_wrapping'])) ? $arrCartInfo['gwPrice'] : 0;
		}
		
		$discount = 0.00;
		$total_amount = $_SESSION['ORDER']['totalPrice'] + $_SESSION['ORDER']['shipping'];
		$this->discount_total($_SESSION['ORDER']['totalPrice'], $discount, $is_fee_shipping, $is_voucher_exist);
		
		$odr_status = '1';
		if (floatval($_SESSION['ORDER']['totalPrice'] + $_SESSION['ORDER']['shipping'] - $discount) < 0){
			$discount = $_SESSION['ORDER']['totalPrice'] + $_SESSION['ORDER']['shipping'];
			$odr_status = '2';
		}
		// Make the order in database(order, order_detail, order_history) and send a email.
		$total_paid = number_format((floatval($total_amount)), 2, '.', '');
		$total_catalog = number_format(floatval($_SESSION['ORDER']['totalPrice'] - $totalWrapping), 2, '.', '');
		$total_real_paid = number_format(floatval($total_paid - $discount), 2, '.', '');
		$obj_currency_code = $this->Database->prepare("SELECT * FROM `tl_currency` WHERE `iso_code`=?")
											->execute($_COOKIE['PAY_CURRENCY']);
		switch (trim($_GET['method']))
		{
			case 'COD':
				// Get the delivery address.
				$arr_delivery = array();
				$obj_delivery_addr = $this->Database->prepare("SELECT * FROM tl_address_book WHERE id=?")
													->execute($_SESSION['ORDER']['address_shipping']);
				if ($obj_delivery_addr->numRows >= 1)
				{
					$arr_delivery = array(
						'dly_firstname' => $obj_delivery_addr->firstname ? $obj_delivery_addr->firstname : '',
						'dly_lastname' => $obj_delivery_addr->lastname ? $obj_delivery_addr->lastname : '',
						'dly_street' => $obj_delivery_addr->street ? $obj_delivery_addr->street : '',
						'dly_city' => $obj_delivery_addr->city ? $obj_delivery_addr->city : '',
						'dly_state' => $obj_delivery_addr->state ? $obj_delivery_addr->state : '',
						'dly_country' => $obj_delivery_addr->country ? $obj_delivery_addr->country : '',
						'dly_postcode' => $obj_delivery_addr->postcode ? $obj_delivery_addr->postcode : '',
						'dly_telephone' => $obj_delivery_addr->telephone ? $obj_delivery_addr->telephone : '',
						'dly_cellphone' => $obj_delivery_addr->cellphone ? $obj_delivery_addr->cellphone : '',
						'dly_email' => $obj_delivery_addr->email ? $obj_delivery_addr->email : '',
						'dly_street_2' => $obj_delivery_addr->street_2 ? $obj_delivery_addr->street_2 : '',
					);
				}
				// Get the billing address.
				$arr_billing = array();
				$obj_billing_addr = $this->Database->prepare("SELECT * FROM tl_address_book WHERE id=?")
													->execute($_SESSION['ORDER']['address_billing']);
				if ($obj_billing_addr->numRows >= 1)
				{
					$arr_billing = array(
						'bill_firstname' => $obj_billing_addr->firstname ? $obj_billing_addr->firstname : '',
						'bill_lastname' => $obj_billing_addr->lastname ? $obj_billing_addr->lastname : '',
						'bill_street' => $obj_billing_addr->street ? $obj_billing_addr->street : '',
						'bill_city' => $obj_billing_addr->city ? $obj_billing_addr->city : '',
						'bill_state' => $obj_billing_addr->state ? $obj_billing_addr->state : '',
						'bill_country' => $obj_billing_addr->country ? $obj_billing_addr->country : '',
						'bill_postcode' => $obj_billing_addr->postcode ? $obj_billing_addr->postcode : '',
						'bill_telephone' => $obj_billing_addr->telephone ? $obj_billing_addr->telephone : '',
						'bill_cellphone' => $obj_billing_addr->cellphone ? $obj_billing_addr->cellphone : '',
						'bill_email' => $obj_billing_addr->email ? $obj_billing_addr->email : '',
						'bill_street_2' => $obj_billing_addr->street_2 ? $obj_billing_addr->street_2 : '',
					);
				}
				
				$objOrder = $this->Database->prepare("INSERT INTO tl_orders (`orderno`, `id_carrier`, `id_lang`, `id_member`, `id_currency`, `id_address_delivery`, `dly_firstname`, `dly_lastname`, `dly_street`, `dly_city`, `dly_state`, `dly_country`, `dly_postcode`, `dly_telephone`, `dly_cellphone`, `dly_email`, `dly_street_2`, `id_address_invoice`, `bill_firstname`, `bill_lastname`, `bill_street`, `bill_city`, `bill_state`, `bill_country`, `bill_postcode`, `bill_telephone`, `bill_cellphone`, `bill_email`, `bill_street_2`, `tstamp`, `payment`, `shipping_id`, `total_discounts`, `total_paid`, `total_paid_real`, `total_catolog`, `total_shipping`, `odr_comments`, `date_add`, `date_upd`, `total_wrapping`, `odr_status`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")
								->execute($id_orderNo, $_SESSION['ORDER']['id_carrier'], 1, $_SESSION['ORDER']['mem_id'], $obj_currency_code->id, $_SESSION['ORDER']['address_shipping'], $arr_delivery['dly_firstname'], $arr_delivery['dly_lastname'], $arr_delivery['dly_street'], $arr_delivery['dly_city'], $arr_delivery['dly_state'], $arr_delivery['dly_country'], $arr_delivery['dly_postcode'], $arr_delivery['dly_telephone'], $arr_delivery['dly_cellphone'], $arr_delivery['dly_email'], $arr_delivery['dly_street_2'], $_SESSION['ORDER']['address_billing'], $arr_billing['bill_firstname'], $arr_billing['bill_lastname'], $arr_billing['bill_street'], $arr_billing['bill_city'], $arr_billing['bill_state'], $arr_billing['bill_country'], $arr_billing['bill_postcode'], $arr_billing['bill_telephone'], $arr_billing['bill_cellphone'], $arr_billing['bill_email'], $arr_billing['bill_street_2'], time(), 'COD', $_SESSION['ORDER']['id_carrier'], $discount, $total_paid, $total_real_paid, $total_catalog, $_SESSION['ORDER']['shipping'], trim($_POST['odr_comments']), date('Y-m-d H:i:s'), date('Y-m-d H:i:s'), $totalWrapping, $odr_status);
				
				$insetId = $objOrder->insertId;
				// order detail.
				$arrCatalog = $_SESSION['cart'];
				foreach ($arrCatalog as $key=>$arrCatalogInfo)
				{
					if ($key == 'sessionID')
						continue;
					// Get catalog size.
					$objCatalogSize = $this->Database->prepare("SELECT * FROM catalog_size WHERE id=?")
													->execute($arrCatalogInfo['size']);
					$strCatalogAttribute = "Color:" . $arrCatalogInfo['colour'] . "\n" . "Size:" . $objCatalogSize->size;
					// Get catalog reference.
					$objCatalog = $this->Database->prepare("SELECT * FROM product_catalog WHERE id=?")
													->execute($arrCatalogInfo['id']);
					$arrCatalogs[$key]['id'] = $arrCatalogInfo['id'];
					$arrCatalogs[$key]['reference'] = $objCatalog->description;
					$arrCatalogs[$key]['colour'] = $arrCatalogInfo['colour'];
					$arrCatalogs[$key]['size'] = $objCatalogSize->size;
					$arrCatalogs[$key]['id_size'] = $arrCatalogInfo['size'];
					$arrCatalogs[$key]['product'] = $objCatalog->name;
					$arrCatalogs[$key]['unit_price'] = $objCatalog->price;
					$arrCatalogs[$key]['quantity'] = $arrCatalogInfo['quantity'];
					$arrCatalogs[$key]['total_price'] = $objCatalog->price * intval($arrCatalogInfo['quantity']);
					$arrCatalogs[$key]['gift_wrapping'] = $arrCatalogInfo['gift_wrapping'];
					$arrCatalogs[$key]['skuid'] = $arrCatalogInfo['skuid'];
					
					$objOrderDetail = $this->Database->prepare("INSERT INTO tl_order_detail (`pid`, `product_catalog_id`, `tstamp`, `product_attribute`, `product_name`, `product_skuid`, `product_quantity`, `product_price`, `product_reference`, `is_package`, `gwPrice`) VALUES (?,?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")
												->execute($insetId, $arrCatalogInfo['id'], time(), $strCatalogAttribute,  $arrCatalogInfo['name'], $arrCatalogInfo['skuid'], $arrCatalogInfo['quantity'], $objCatalog->price, $objCatalog->description, intval($arrCatalogInfo['gift_wrapping']), $arrCatalogInfo['gwPrice']);
				}
				
				// order history
				$objOrderHistory = $this->Database->prepare("INSERT INTO tl_order_history (`id_order`, `id_order_state`, `date_add`) VALUES(?, ?, ?)")
												->execute($insetId, 1, date('Y-m-d H:i:s'));
				
				$orderId = intval($insetId);
				$member_id = $_SESSION['ORDER']['mem_id'];
				break;
			case 'Alipay':
			case 'Paypal':				
				// Get the delivery address.
				$arr_delivery = array();
				$obj_delivery_addr = $this->Database->prepare("SELECT * FROM tl_address_book WHERE id=?")
													->execute($_SESSION['ORDER']['address_shipping']);
				if ($obj_delivery_addr->numRows >= 1)
				{
					$arr_delivery = array(
						'dly_firstname' => $obj_delivery_addr->firstname ? $obj_delivery_addr->firstname : '',
						'dly_lastname' => $obj_delivery_addr->lastname ? $obj_delivery_addr->lastname : '',
						'dly_street' => $obj_delivery_addr->street ? $obj_delivery_addr->street : '',
						'dly_city' => $obj_delivery_addr->city ? $obj_delivery_addr->city : '',
						'dly_state' => $obj_delivery_addr->state ? $obj_delivery_addr->state : '',
						'dly_country' => $obj_delivery_addr->country ? $obj_delivery_addr->country : '',
						'dly_postcode' => $obj_delivery_addr->postcode ? $obj_delivery_addr->postcode : '',
						'dly_telephone' => $obj_delivery_addr->telephone ? $obj_delivery_addr->telephone : '',
						'dly_cellphone' => $obj_delivery_addr->cellphone ? $obj_delivery_addr->cellphone : '',
						'dly_email' => $obj_delivery_addr->email ? $obj_delivery_addr->email : '',
						'dly_street_2' => $obj_delivery_addr->street_2 ? $obj_delivery_addr->street_2 : '',
					);
				}
				// Get the billing address.
				$arr_billing = array();
				$obj_billing_addr = $this->Database->prepare("SELECT * FROM tl_address_book WHERE id=?")
													->execute($_SESSION['ORDER']['address_billing']);
				if ($obj_billing_addr->numRows >= 1)
				{
					$arr_billing = array(
						'bill_firstname' => $obj_billing_addr->firstname ? $obj_billing_addr->firstname : '',
						'bill_lastname' => $obj_billing_addr->lastname ? $obj_billing_addr->lastname : '',
						'bill_street' => $obj_billing_addr->street ? $obj_billing_addr->street : '',
						'bill_city' => $obj_billing_addr->city ? $obj_billing_addr->city : '',
						'bill_state' => $obj_billing_addr->state ? $obj_billing_addr->state : '',
						'bill_country' => $obj_billing_addr->country ? $obj_billing_addr->country : '',
						'bill_postcode' => $obj_billing_addr->postcode ? $obj_billing_addr->postcode : '',
						'bill_telephone' => $obj_billing_addr->telephone ? $obj_billing_addr->telephone : '',
						'bill_cellphone' => $obj_billing_addr->cellphone ? $obj_billing_addr->cellphone : '',
						'bill_email' => $obj_billing_addr->email ? $obj_billing_addr->email : '',
						'bill_street_2' => $obj_billing_addr->street_2 ? $obj_billing_addr->street_2 : '',
					);
				}
				
				$objOrder = $this->Database->prepare("INSERT INTO tl_orders (`orderno`, `id_carrier`, `id_lang`, `id_member`, `id_currency`, `id_address_delivery`, `dly_firstname`, `dly_lastname`, `dly_street`, `dly_city`, `dly_state`, `dly_country`, `dly_postcode`, `dly_telephone`, `dly_cellphone`, `dly_email`, `dly_street_2`, `id_address_invoice`, `bill_firstname`, `bill_lastname`, `bill_street`, `bill_city`, `bill_state`, `bill_country`, `bill_postcode`, `bill_telephone`, `bill_cellphone`, `bill_email`, `bill_street_2`, `tstamp`, `payment`, `shipping_id`, `total_discounts`, `total_paid`, `total_paid_real`, `total_catolog`, `total_shipping`, `odr_comments`, `date_add`, `date_upd`, `total_wrapping`, `odr_status`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")
								->execute($id_orderNo, $_SESSION['ORDER']['id_carrier'], 1, $_SESSION['ORDER']['mem_id'], $obj_currency_code->id, $_SESSION['ORDER']['address_shipping'], $arr_delivery['dly_firstname'], $arr_delivery['dly_lastname'], $arr_delivery['dly_street'], $arr_delivery['dly_city'], $arr_delivery['dly_state'], $arr_delivery['dly_country'], $arr_delivery['dly_postcode'], $arr_delivery['dly_telephone'], $arr_delivery['dly_cellphone'], $arr_delivery['dly_email'], $arr_delivery['dly_street_2'], $_SESSION['ORDER']['address_billing'], $arr_billing['bill_firstname'], $arr_billing['bill_lastname'], $arr_billing['bill_street'], $arr_billing['bill_city'], $arr_billing['bill_state'], $arr_billing['bill_country'], $arr_billing['bill_postcode'], $arr_billing['bill_telephone'], $arr_billing['bill_cellphone'], $arr_billing['bill_email'], $arr_billing['bill_street_2'], time(), $_GET['method'], $_SESSION['ORDER']['id_carrier'], $discount, $total_paid, $total_real_paid, $total_catalog, $_SESSION['ORDER']['shipping'], trim($_POST['odr_comments']), date('Y-m-d H:i:s'), date('Y-m-d H:i:s'), $totalWrapping, $odr_status);
				
				$insetId = $objOrder->insertId;	
				// order detail.
				$arrCatalog = $_SESSION['cart'];
				foreach ($arrCatalog as $key=>$arrCatalogInfo)
				{
					if ($key == 'sessionID')
						continue;
					// Get catalog size.
					$objCatalogSize = $this->Database->prepare("SELECT * FROM catalog_size WHERE id=?")
													->execute($arrCatalogInfo['size']);
					$strCatalogAttribute = "Color:" . $arrCatalogInfo['colour'] . "\n" . "Size:" . $objCatalogSize->size;
					// Get catalog reference.
					$objCatalog = $this->Database->prepare("SELECT * FROM product_catalog WHERE id=?")
													->execute($arrCatalogInfo['id']);
					$arrCatalogs[$key]['id'] = $arrCatalogInfo['id'];
					$arrCatalogs[$key]['reference'] = $objCatalog->description;
					$arrCatalogs[$key]['colour'] = $arrCatalogInfo['colour'];
					$arrCatalogs[$key]['size'] = $objCatalogSize->size;
					$arrCatalogs[$key]['id_size'] = $arrCatalogInfo['size'];
					$arrCatalogs[$key]['product'] = $objCatalog->name;
					$arrCatalogs[$key]['unit_price'] = $objCatalog->price;
					$arrCatalogs[$key]['quantity'] = $arrCatalogInfo['quantity'];
					$arrCatalogs[$key]['total_price'] = $objCatalog->price * intval($arrCatalogInfo['quantity']);
					$arrCatalogs[$key]['gift_wrapping'] = $arrCatalogInfo['gift_wrapping'];
					$arrCatalogs[$key]['skuid'] = $arrCatalogInfo['skuid'];
					
					$objOrderDetail = $this->Database->prepare("INSERT INTO tl_order_detail (`pid`, `product_catalog_id`, `tstamp`, `product_attribute`, `product_name`, `product_skuid`, `product_quantity`, `product_price`, `product_reference`, `is_package`, `gwPrice`) VALUES (?,?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")
												->execute($insetId, $arrCatalogInfo['id'], time(), $strCatalogAttribute,  $arrCatalogInfo['name'], $arrCatalogInfo['skuid'], $arrCatalogInfo['quantity'], $objCatalog->price, $objCatalog->description, intval($arrCatalogInfo['gift_wrapping']), $arrCatalogInfo['gwPrice']);
				}
				
				// order history
				$objOrderHistory = $this->Database->prepare("INSERT INTO tl_order_history (`id_order`, `id_order_state`, `date_add`) VALUES(?, ?, ?)")
												->execute($insetId, 1, date('Y-m-d H:i:s'));
				
				$orderId = intval($insetId);
				$member_id = $_SESSION['ORDER']['mem_id'];
				break;
			default:
				break;
		}
		
		// Send Email
		$email = new Email();
		
		$email->subject = "Your order is being processed";
		$email->from = $GLOBALS['TL_CONFIG']['adminEmail'];
		$email->fromName = "Daftshopping.com";
		$replyTo = "34n.sam@gmail.com" . '<34n.sam@gmail.com>';
		
		// Parse the params.
		$shopName = "Daft";
		$id_order = $orderId;
		$orderNumber = $id_orderNo;
		$shopurl = $this->Environment->base;
		$shoplog = $this->Environment->base . 'images/logo_order.jpg';
		$footerImg = $this->Environment->base . 'images/footer_log.jpg';
		$img_email_conf = $this->Environment->base . '?inlink=email_cfm';
		
		// Get delivery address.
		$objShipping = $this->Database->prepare("SELECT tl_address_book.*,china_province.province_en,china_city.city_en FROM tl_address_book 
												LEFT JOIN china_province ON china_province.id=tl_address_book.state
												LEFT JOIN china_city ON china_city.id=tl_address_book.city
												WHERE tl_address_book.id=?")
									->execute($_SESSION['ORDER']['address_shipping']);
		$delivery_firstname = $objShipping->firstname;
		$delivery_lastname = $objShipping->lastname;
		$delivery_address1 = $objShipping->street;
		$delivery_address2 = $objShipping->street_2;
		$delivery_city = $objShipping->city_en;
		$delivery_postal_code = $objShipping->postcode;
		$delivery_country = $objShipping->country;
		$delivery_state = $objShipping->province_en;
		$delivery_phone = $objShipping->telephone;
		if ($objShipping->country != 'cn'){
			$objShipping = $this->Database->prepare("SELECT * FROM `tl_address_book` WHERE `id`=?")
										->execute($_SESSION['ORDER']['address_shipping']);
			$delivery_state = $objShipping->state;
			$delivery_city = $objShipping->city;
		}
		
		// Get the member info.
		$objMember = $this->Database->prepare("SELECT tl_member.*,china_province.province_en,china_city.city_en FROM tl_member 
												LEFT JOIN china_province ON china_province.id=tl_member.state
												LEFT JOIN china_city ON china_city.id=tl_member.city
												WHERE tl_member.id=?")
									->execute($_SESSION['ORDER']['mem_id']);
		$firstname = $objMember->firstname;
		$lastname = $objMember->lastname;
		$invoice_email = $objMember->email;
		
		$objShipping = $this->Database->prepare("SELECT tl_address_book.*,china_province.province_en,china_city.city_en FROM tl_address_book 
												LEFT JOIN china_province ON china_province.id=tl_address_book.state
												LEFT JOIN china_city ON china_city.id=tl_address_book.city
												WHERE tl_address_book.id=?")
									->execute($_SESSION['ORDER']['address_billing']);
		$delivery_firstname_bill = $objShipping->firstname;
		$delivery_lastname_bill = $objShipping->lastname;
		$delivery_address1_bill = $objShipping->street;
		$delivery_address2_bill = $objShipping->street_2;
		$delivery_city_bill = $objShipping->city_en;
		$delivery_postal_code_bill = $objShipping->postcode;
		$delivery_country_bill = $objShipping->country;
		$delivery_state_bill = $objShipping->province_en;
		$delivery_phone_bill = $objShipping->telephone;	
		if ($objShipping->country != 'cn'){
			$objShipping = $this->Database->prepare("SELECT * FROM `tl_address_book` WHERE `id`=?")
										->execute($_SESSION['ORDER']['address_billing']);
			$delivery_state_bill = $objShipping->state;
			$delivery_city_bill = $objShipping->city;
		}
		
		// Comments and requests.
		$invoice_tbls = "<table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\"><tr><td><strong>PAYMENT METHOD </strong><p>" . trim($_GET['method']) . "</p><br/><br/><br/>
						<strong>Comments or Special Request</strong><p>" . (($_POST['odr_comments'] == 'FOR EXAMPLE: PLEASE DELIVER BETWEEN 7 AND 9PM IN THE EVENING') ? '' : trim($_POST['odr_comments'])) . "</p></td></tr></table>";
			
		$delivery_tbls = "<table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\">
						<tr>
						<td>
							<strong>SHIPPING ADDRESS</strong>
							<p>" . $delivery_firstname . ' ' . $delivery_lastname . "<br/>
								" . $delivery_address1 . " <br/>" . (($delivery_address2) ? $delivery_address2 . '<br />' : '') . $delivery_city . " " . $delivery_state . " " . $delivery_country . " " . $delivery_postal_code . "</p><br/>
								<strong>BILLING ADDRESS</strong><p>" . $delivery_firstname_bill . ' ' . $delivery_lastname_bill . "<br/>" . $delivery_address1_bill . " <br/>
								" . (($delivery_address2_bill) ? $delivery_address2_bill . '<br />' : '') . $delivery_city_bill . " " . $delivery_state_bill . " " . $delivery_country_bill . " " . $delivery_postal_code_bill . "</p>
						</td>
						</tr>
					</table>";
		
		// Mail product html	
		$tbl_products_left .= "<table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\"><tr><td colspan=\"6\" height=\"15\">
									<tr>
										<td><img alt=\"\" src=\"" . $this->Environment->base . "images/spacer.gif\" width=\"320\" height=\"22\" style=\"border:none;\" /></td>
										<td><img alt=\"\" src=\"" . $this->Environment->base . "images/spacer.gif\" width=\"130\" height=\"5\" style=\"border:none;\" /></td>
										<td><img alt=\"\" src=\"" . $this->Environment->base . "images/spacer.gif\" width=\"50\" height=\"5\" style=\"border:none;\" /></td>
										<td><img alt=\"\" src=\"" . $this->Environment->base . "images/spacer.gif\" width=\"40\" height=\"5\" style=\"border:none;\" /></td>
										<td><img alt=\"\" src=\"" . $this->Environment->base . "images/spacer.gif\" width=\"70\" height=\"5\" style=\"border:none;\" /></td>
										<td><img alt=\"\" src=\"" . $this->Environment->base . "images/spacer.gif\" width=\"90\" height=\"5\" style=\"border:none;\" /></td>
									</tr>
									<tr>
										<td width=\"500\"><strong>SKU &amp; Name</strong></td>
										<td width=\"14%\"><strong>Color</strong></td>
										<td width=\"10%\"><strong>Size</strong></td>
										<td width=\"6%\"><strong>QTN</strong></td>
										<td width=\"10%\"><div align=\"right\"><strong>PRICE</strong></div></td>
										<td width=\"14%\"><div align=\"right\"><strong>SUBTOTAL</strong></div></td>
									</tr>";
		
		foreach ($arrCatalogs as $strCatalogInfo)
		{
			$tbl_products_left .= "<tr>
				<td>" . $strCatalogInfo['skuid'] . "<br />" . $strCatalogInfo['product'] . "<p>&nbsp;</p></td>
				<td width=\"14%\">" . $strCatalogInfo['colour'] . "</td>
				<td width=\"10%\">" . $strCatalogInfo['size'] . "</td>
				<td width=\"6%\">" . $strCatalogInfo['quantity'] . "</td>
				<td width=\"10%\"><div align=\"right\">" . $this->obj_currency->change_order(number_format($strCatalogInfo['unit_price'], 2, '.', ''),$_COOKIE['PAY_CURRENCY']) . "</div></td>
				<td width=\"14%\"><div align=\"right\">" . $this->obj_currency->change_order(number_format($strCatalogInfo['total_price'], 2, '.', ''),$_COOKIE['PAY_CURRENCY']) . "</div></td>
			</tr>";				
		
		}
		$tbl_products_left .= "<tr><td height=\"20\" colspan=\"6\"></td></tr></table>";
		
		// Get shipping method.
		$obj_shippings = $this->Database->prepare("SELECT * FROM `tl_shippings` WHERE `tl_shippings`.`id`=?")
										->execute($_SESSION['ORDER']['id_carrier'],time(),time());
		$tbl_products_right .= "<table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\">
									<tr>
										<td><img alt=\"\" src=\"" . $this->Environment->base . "images/spacer.gif\" width=\"375\" height=\"5\" style=\"border:none;\" /></td>
                                        <td colspan=\"2\"><img alt=\"\" src=\"" . $this->Environment->base . "images/singleline.gif\" width=\"325\" height=\"9\" style=\"border:none;\" /></td>
									</tr> 
									<tr>
										<td height=\"15\">&nbsp;</td>
										<td width=\"185\">SUBTOTAL:</td><td width=\"114\" class=\"text_r\">" . $this->obj_currency->change_order($total_catalog,$_COOKIE['PAY_CURRENCY']) . "</td>
									</tr>
									<tr>
										<td height=\"15\">&nbsp;</td>
										<td>GIFT WRAPPING:</td><td class=\"text_r\">" . $this->obj_currency->change_order(number_format($totalWrapping, 2, '.', ''),$_COOKIE['PAY_CURRENCY']) . "</td>
									</tr>
									<tr>
										<td height=\"15\">&nbsp;</td>
										<td>" . $obj_shippings->name . ":</td><td class=\"text_r\">" . $this->obj_currency->change_order(number_format($_SESSION['ORDER']['shipping'], 2, '.', ''),$_COOKIE['PAY_CURRENCY'])
									 . "</td></tr><tr><td colspan=\"6\" height=\"20\"></td>
									</tr>" . (($discount != "0.00") ? "<tr><td height=\"15\">&nbsp;</td><td>GIFT VOUCHER:</td><td class=\"text_r\">" . $this->obj_currency->change_order(number_format($discount, 2, '.', ''),$_COOKIE['PAY_CURRENCY']) . "</td></tr>" : "") . "
									<tr>
										<td><img alt=\"\" src=\"" . $this->Environment->base . "images/spacer.gif\" width=\"375\" height=\"20\" style=\"border:none;\" /></td>
										<td colspan=\"2\"><img alt=\"\" src=\"" . $this->Environment->base . "images/spacer.gif\" width=\"325\" height=\"5\" style=\"border:none;\" /></td>
									</tr>
									<tr>
										<td height=\"15\">&nbsp;</td>
										<td><strong>TOTAL:</strong></td><td class=\"text_r\"><strong>" . $this->obj_currency->change_order(number_format($total_real_paid, 2, '.', ''),$_COOKIE['PAY_CURRENCY']) . "</strong></td>
									</tr>
									<tr>
  										<td height=\"15\" colspan=\"3\"><img alt=\"\" src=\"" . $this->Environment->base . "images/spacer.gif\" style=\"width:1;height:22;border:none;\" /></td>
									  </tr>
								</table>";
		
		$total_products = $total_catalog;
		$total_shipping = $_SESSION['ORDER']['shipping'];		
		
		$total_paid = $total_real_paid;
		$payment = trim($_GET['method']);
		
		if (isset($_POST['vourcher'])&&$_POST['vourcher'])
		{
			// Make the voucher status.
			$objVoucher = $this->Database->prepare("UPDATE `tl_voucher` SET `current_use`=`current_use`+1 WHERE `coupon_code`=?")
										->execute(0, strtoupper($this->Input->post('vourcher')));
		}
									
		//print_r($objVoucher);exit;
		ob_start();
		include(TL_ROOT . "/mails/" . $GLOBALS['TL_LANGUAGE'] . "/order_conf.php");
		$strBuffer = ob_get_contents();
		ob_end_clean();
		
		$email->html = $strBuffer;
		$email->sendTo($invoice_email);	
		
		// To administrator
		$email->sendTo($GLOBALS['TL_CONFIG']['feedback_recieve']);
		
		
		// Update the stock of product.
		foreach ($arrCatalogs as $strCatalogInfo)
		{
			$strSQL = "SELECT `id` FROM `catalog_colour` WHERE `title`=?";
			$objColorInfo = $this->Database->prepare($strSQL)
											->execute($strCatalogInfo['colour']);
									
			$strSQL = "UPDATE `tl_catalog_attribute` SET `catalog_stock`=`catalog_stock`-" . $strCatalogInfo['quantity'] . " WHERE `id_catalog`=? AND `id_color`=? AND `id_size`=?";
			$objUpdateStock = $this->Database->prepare($strSQL)
											->execute($strCatalogInfo['id'], $objColorInfo->id, $strCatalogInfo['id_size']);
		}
		// Update end.
		
		if ($_POST['is_paypal_fast'])
		{
			unset($_SESSION['cart']);
			unset($_SESSION['ORDER']);
			unset($_SESSION['CARTQUANTITY']);
			
			$this->ec_paypal($orderId, $total_paid,$this->Environment->base."thankyou_others.html?id_order=" . $orderId . "&id_member=" . $member_id . "&orderno=" . $id_orderNo);
			$this->redirect("thankyou_others.html?id_order=" . $orderId . "&id_member=" . $member_id . "&orderno=" . $id_orderNo);exit;
		}
		
		if (trim($_GET['method']) == 'COD')
		{
			unset($_SESSION['cart']);
			unset($_SESSION['ORDER']);
			unset($_SESSION['CARTQUANTITY']);
			
			$this->redirect("thankyou_others.html?id_order=" . $orderId . "&id_member=" . $member_id . "&orderno=" . $id_orderNo);
		}
		else
		{
			switch (trim($_GET['method']))
			{
				case 'Alipay':
					$strHtml = $this->generateAlipayForm($orderId, $discount);
					break;
				case 'Paypal':
					$strHtml = $this->generatePaypalForm($orderId, $discount);
					break;
			}
			echo $strHtml;exit;
		}
	}
	
	private function ec_paypal($orderId, $total_paid,$return='')
	{		
		$shopname = 'daftshopping';
		$this->import("Database");
		if (!$_COOKIE['PAY_CURRENCY']){
			$objSession = $this->Database->prepare("SELECT * FROM tl_session WHERE hash=? AND name=?")
										->execute($_COOKIE['FE_USER_AUTH'], 'FE_USER_AUTH');
			$obj_member = $this->Database->prepare("SELECT * FROM tl_member WHERE id=?")
										->execute($objSession->pid);
			$preferred = ($obj_member->cur)?$obj_member->cur:$_COOKIE['DAFT_CURRENCY'];
			if (!$preferred){
				$obj_currency = $this->Database->prepare("SELECT * FROM `tl_currency` WHERE `is_default`=1")
												->execute(time());
				
				$preferred = $obj_currency->iso_code;
			}
			
			setcookie("PAY_CURRENCY", $preferred);
		}
        
        $currencyCodeType = $_COOKIE['PAY_CURRENCY'];
		$obj_currency = $this->Database->prepare("SELECT * FROM `tl_currency` WHERE `iso_code`=?")
												->execute($_COOKIE['PAY_CURRENCY']);
		
		$token = urlencode($_SESSION['reshash']['TOKEN']);
        $paymentAmount = urlencode((float)($total_paid*$obj_currency->conversion_rate));
        $paymentType = 'Sale';
        $currCodeType = urlencode($currencyCodeType);
        $payerID = urlencode($_SESSION['reshash']['PAYERID']);
        $serverName = urlencode($_SERVER['SERVER_NAME']);
        $nvpstr='&TOKEN='.$token.'&PAYERID='.$payerID.'&PAYMENTACTION='.$paymentType.'&AMT='.$paymentAmount.'&CURRENCYCODE='.$currCodeType.'&IPADDRESS='.$serverName;
        $resArray = $this->hash_call("DoExpressCheckoutPayment",$nvpstr);
        $ack = strtoupper($resArray["ACK"]);
		
		if($ack=="SUCCESS")
		{
			unset($_SESSION['reshash']);
			unset($_SESSION['ORDER']['is_paypal_fast']);			
			unset($_SESSION['paypal_params']);
			
            // PAY SUCCESS.
			$this->import("Database");
			$obj_order = $this->Database->prepare("SELECT * FROM `tl_orders` WHERE `id`=?")
												->execute($orderId);
			if ($obj_order->numRows >= 1)
			{
				$obj_order = $this->Database->prepare("UPDATE `tl_orders` SET `odr_status`='2' WHERE `id`=?")
												->execute($orderId);
				$obj_order_history = $this->Database->prepare("UPDATE `tl_order_history` SET `id_order_state`='2' WHERE `id_order`=?")
												->execute($orderId);
				
				require_once(TL_ROOT.'/templates/validationPaypal.php');
				$obj_send_email = new ValidationPaypal();
				$obj_send_email->send_email($orderId);
			}				
		}
		else
		{
			$this->redirect("thankyou_others.html?id_order=" . $orderId . "&id_member=" . $member_id . "&orderno=" . $id_orderNo);
		}
	}
	
	private function hash_call($methodName,$nvpStr)
	{
		include_once(TL_ROOT.'/templates/ecpaypal/defined.php');
        $API_UserName = PAYPAL_MEMBERID;
        $API_Password = PAYPAL_PASSWORD;
        $API_Signature = PAYPAL_SIGNATURE;
		$API_Endpoint = API_ENDPOINT;
		
        $version = '57.0';
        /*
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,$API_Endpoint);
        curl_setopt($ch, CURLOPT_VERBOSE, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
        curl_setopt($ch, CURLOPT_POST, 1);*/
        //if(USE_PROXY)
       // curl_setopt ($ch, CURLOPT_PROXY, PROXY_HOST.":".PROXY_PORT);
        $nvpreq = "METHOD=".urlencode($methodName)."&VERSION=".urlencode($version)."&PWD=".urlencode($API_Password)."&USER=".urlencode($API_UserName)."&SIGNATURE=".urlencode($API_Signature).$nvpStr;
        #print_r($nvpreq);exit;
		$request = new Request();
		$request->send($API_Endpoint,$nvpreq,'POST');
		$nvpResArray = $this->deformatNVP($request->response);
        $nvpReqArray = $this->deformatNVP($nvpreq);
		$_SESSION['nvpReqArray'] = $nvpReqArray;
		
		return $nvpResArray;
	}
	
	private function deformatNVP($nvpstr)
    {
        $intial=0;
        $nvpArray = array();
        while(strlen($nvpstr))
        {
            $keypos= strpos($nvpstr,'=');
            $valuepos = strpos($nvpstr,'&') ? strpos($nvpstr,'&'): strlen($nvpstr);
            $keyval=substr($nvpstr,$intial,$keypos);
            $valval=substr($nvpstr,$keypos+1,$valuepos-$keypos-1);
            $nvpArray[urldecode($keyval)] =urldecode( $valval);
            $nvpstr=substr($nvpstr,$valuepos+1,strlen($nvpstr));
        }
        return $nvpArray;
    }
	
	/**
	 * This function get the stock of this special product and current quantity.
	 * @param int $id_catalog
	 * @param string $colour
	 * @param int $size
	 * @return int currentStock
	 */
	public function getCurrentStockInfo($id_catalog=0, $colour=0, $size=0)
	{
		if (!$id_catalog || !$colour || !$size)
			return null;
		// Get the colour id.
		$this->import("Database");
		$strSQL = "SELECT `id` FROM `catalog_colour` WHERE `title`=?";
		$objId_colour = $this->Database->prepare($strSQL)
							->execute($colour, time(), time());
		
		if ($objId_colour->numRows < 1)
			return null;
		
		$id_colour = $objId_colour->id;
		
		// Get the stock of this special product.
		$strSQL = "SELECT * FROM `tl_catalog_attribute` WHERE `id_catalog`=? AND `id_color`=? AND `id_size`=?";
		$objSock = $this->Database->prepare($strSQL)
								->execute($id_catalog, $id_colour, $size);
		if ($objSock->numRows < 1)
			return null;
		
		$cnt_stock = intval($objSock->catalog_stock);
		
		return $cnt_stock;
	}		
}

$validation = new Validation();
$validation->run();
	
?>